agilira/balios
GitHub: agilira/balios
基于 W-TinyLFU 算法的 Go 高性能内存缓存库,兼顾吞吐量、命中率与安全性。
Stars: 6 | Forks: 1
# Balios:适用于 Go 的高性能缓存库

Balios 是一个适用于 Go 的高性能内存缓存库,基于 W-TinyLFU 算法,专为最大化吞吐量、最佳命中率、专业安全性和高级可观测性而设计——同时不牺牲开发者体验。
[](https://github.com/agilira/balios/actions/workflows/ci.yml)
[](https://github.com/agilira/balios/actions/workflows/codeql.yml)
[](https://github.com/agilira/balios/actions/workflows/ci.yml)
[](https://goreportcard.com/report/github.com/agilira/balios)
[](https://github.com/agilira/balios)
[](https://www.bestpractices.dev/projects/11297)
**[特性](#features) • [快速开始](#quick-start) • [性能表现](#performance) • [可观测性架构](#observability-architecture) • [设计理念](#the-philosophy-behind-balios) • [文档](#documentation)**
## 特性
- **类型安全的泛型 API**:具有编译时类型安全的 `GenericCache[K comparable, V any]`
- **自动加载**:带有 singleflight 模式的 `GetOrLoad()` API,可防止缓存击穿
- **W-TinyLFU 算法**:结合频率和近因性以做出最佳的驱逐决策
- **无锁**:使用原子原语实现高并发
- **TTL 支持**:混合过期策略,结合内联机会性清理和手动 `ExpireNow()` API(v1.1.32+)
- **Context 支持**:支持加载器函数的超时和取消
- **负缓存**:缓存加载器错误以防止重复的失败操作(v1.1.2+)
- **结构化错误**:通过 [go-errors](https://github.com/agilira/go-errors) 提供丰富的错误上下文 - 参见 [examples/errors/](examples/errors/)
- **可观测性**:集成 OpenTelemetry 以获取指标(p50/p95/p99 延迟、命中率)和日志接口。禁用时零开销(编译器会消除无操作实现) - 参见 [examples/otel-prometheus/](examples/otel-prometheus/)
- **安全设计**:经过[红队测试](balios_security_test.go)和[模糊测试](balios_fuzz_test.go),可抵御各种攻击
## 兼容性与支持
Balios 专为 Go 1.24+ 环境设计,并遵循长期支持指导原则,以确保在生产部署中保持一致的性能。
## 安装
```
go get github.com/agilira/balios
```
## 快速开始
### 类型安全的泛型 API
```
package main
import (
"fmt"
"time"
"github.com/agilira/balios"
)
type User struct {
ID int
Name string
Role string
}
func main() {
// Create type-safe cache
cache := balios.NewGenericCache[string, User](balios.Config{
MaxSize: 10_000,
TTL: time.Hour,
})
// Set a value
cache.Set("user:123", User{
ID: 123,
Name: "John Doe",
Role: "admin",
})
// Get a value (no type assertion needed)
if user, found := cache.Get("user:123"); found {
fmt.Printf("User: %s (%s)\n", user.Name, user.Role)
}
// Check stats
stats := cache.Stats()
fmt.Printf("Hit ratio: %.2f%%\n", stats.HitRatio()*100)
}
```
## 性能表现
**单线程性能:**
| Package | Set (ns/op) | Set % vs Balios | Get (ns/op) | Get % vs Balios | Allocations |
| :------ | ----------: | --------------: | ----------: | --------------: | ----------: |
| **Balios** | **194.4 ns/op** | **+0%** | **110.8 ns/op** | **+0%** | **2/0 allocs/op** |
| Balios-Generic | 198.2 ns/op | +2% | 115.0 ns/op | +4% | 2/0 allocs/op |
| Otter | 365.3 ns/op | +88% | 121.2 ns/op | +9% | 1/0 allocs/op |
| Ristretto | 280.0 ns/op | +44% | 156.7 ns/op | +41% | 2/0 allocs/op |
**并行性能(8核):**
| Package | Set (ns/op) | Set % vs Balios | Get (ns/op) | Get % vs Balios | Allocations |
| :------ | ----------: | --------------: | ----------: | --------------: | ----------: |
| **Balios** | **59.26 ns/op** | **+0%** | **25.50 ns/op** | **+0%** | **2/0 allocs/op** |
| Balios-Generic | 60.84 ns/op | +3% | 27.33 ns/op | +7% | 2/0 allocs/op |
| Otter | 240.1 ns/op | +305% | 25.78 ns/op | +1% | 1/0 allocs/op |
| Ristretto | 115.1 ns/op | +94% | 30.04 ns/op | +18% | 1/0 allocs/op |
**混合工作负载(真实场景):**
| Workload | Balios | Balios-Generic | Otter | Ristretto | Best |
| :------- | -----: | -------------: | ----: | --------: | :--- |
| 写多读少 (10% R / 90% W) | **85.82 ns/op** | 100.7 ns/op | 210.3 ns/op | 125.4 ns/op | **Balios** |
| 读写均衡 (50% R / 50% W) | **50.01 ns/op** | 52.81 ns/op | 132.5 ns/op | 113.2 ns/op | **Balios** |
| 读多写少 (90% R / 10% W) | **35.08 ns/op** | 36.84 ns/op | 47.64 ns/op | 70.81 ns/op | **Balios** |
| 只读 (100% R) | **36.59 ns/op** | 55.91 ns/op | 46.95 ns/op | 31.63 ns/op | **Ristretto** |
**命中率(10万次请求,Zipf 分布):**
| Cache | Hit Ratio | Notes |
| :---- | --------: | :---- |
| **Balios** | 79.86% | 优秀 |
| Balios-Generic | 79.71% | 优秀 |
| **Otter** | 79.53% | 优秀 |
| Ristretto | 71.19% | 良好 |
**测试环境:** AMD Ryzen 5 7520U, Go 1.25+
在你的硬件上运行基准测试 [benchmarks/](benchmarks/),以评估在特定工作负载和配置下的性能。
详细的分析和方法论请参见 [docs/PERFORMANCE.md](docs/PERFORMANCE.md)。
### 高级配置
**负缓存** (v1.1.2+):缓存加载器错误以防止重复的失败操作
```
cache := balios.NewGenericCache[int, User](balios.Config{
MaxSize: 10_000,
TTL: 5 * time.Minute,
NegativeCacheTTL: 30 * time.Second, // Cache errors for 30s
})
// First call: loader fails
_, err := cache.GetOrLoad(123, func() (User, error) {
return User{}, fmt.Errorf("database unavailable")
})
// Error returned
// Subsequent calls within 30s: cached error returned WITHOUT calling loader
_, err = cache.GetOrLoad(123, func() (User, error) {
panic("This won't be called - error is cached!")
})
// Same error returned (no loader execution)
```
**用例**:熔断器模式、API 速率限制、外部服务故障。
**参见**:[GetOrLoad 文档](docs/GETORLOAD.md#negative-caching-v112) 获取完整指南。
### 使用 GetOrLoad 自动加载
使用 singleflight 模式防止缓存击穿:
```
// Multiple concurrent requests for same key = single loader execution
user, err := cache.GetOrLoad("user:123", func() (User, error) {
// This expensive operation runs only once
return fetchUserFromDB(123)
})
if err != nil {
log.Printf("Failed to load user: %v", err)
return
}
```
带有支持超时/取消的 Context:
```
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
user, err := cache.GetOrLoadWithContext(ctx, "user:123",
func(ctx context.Context) (User, error) {
return fetchUserFromDBWithContext(ctx, 123)
})
```
**主要特性:**
- 缓存命中:与 `Get()` 操作性能相同(并行 27.90 ns/op,0 次内存分配)
- 并发请求:1000 个同时发生的请求 = 1 次加载器调用(singleflight)
- 错误处理:可以使用 `NegativeCacheTTL` 选项缓存加载器错误
- Panic 恢复:如果加载器发生 panic,返回 `BALIOS_PANIC_RECOVERED` 错误
更多综合示例请参见 [examples/getorload/](examples/getorload/)。
## 可观测性架构
```
graph TB
subgraph "Core Cache Module"
CACHE[Balios Cache
Get/Set/Delete Operations] IFACE[MetricsCollector Interface
Thread-Safe API] NOOP[NoOpMetricsCollector
Zero Overhead Default
Compiler Inlined] end subgraph "Implementation Layer" OTEL[OpenTelemetry Collector
otel package
Professional Metrics] CUSTOM[Custom Collector
User Implementation
Domain-Specific] end subgraph "Observability Backends" PROM[Prometheus
Metrics Storage
Time-Series DB] JAEGER[Jaeger
Distributed Tracing
Performance Analysis] GRAFANA[Grafana
Visualization
Dashboards] end subgraph "Custom Integrations" DD[DataDog
APM Platform] CUSTOM_BACK[Custom Backend
Internal Tools
Domain-Specific] end %% Connections CACHE --> IFACE IFACE --> NOOP IFACE --> OTEL IFACE --> CUSTOM OTEL --> PROM OTEL --> JAEGER PROM --> GRAFANA CUSTOM --> DD CUSTOM --> CUSTOM_BACK %% Styling with Argus color scheme classDef core fill:#ecfdf5,stroke:#059669,stroke-width:2px classDef implementation fill:#f0f9ff,stroke:#0369a1,stroke-width:2px classDef observability fill:#fef3c7,stroke:#d97706,stroke-width:2px classDef custom fill:#f3e8ff,stroke:#7c3aed,stroke-width:2px class CACHE,IFACE,NOOP core class OTEL,CUSTOM implementation class PROM,JAEGER,GRAFANA observability class DD,CUSTOM_BACK custom ``` ### Logger 接口 ``` // Logger defines a minimal logging interface with zero overhead. // Implementations should use structured logging and be allocation-free. type Logger interface { // Debug logs a debug message with optional key-value pairs. Debug(msg string, keyvals ...interface{}) // Info logs an info message with optional key-value pairs. Info(msg string, keyvals ...interface{}) // Warn logs a warning message with optional key-value pairs. Warn(msg string, keyvals ...interface{}) // Error logs an error message with optional key-value pairs. Error(msg string, keyvals ...interface{}) } ``` **集成示例:** ``` import "log/slog" // Using standard library slog logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) cache := balios.New[string, User](balios.Config{ Size: 1000, Logger: logger, }) ``` 完整文档请参见 [指标与可观测性](docs/METRICS.md)。 ## Balios 背后的理念 Balios 和他的兄弟 Xanthos 是 Achilles 的不朽战马,由风神中最迅捷的 Zephyros 所生。它们不仅仅是快——它们是风本身的孩子,凡间马匹无法比拟。Balios 拥有超越任何马匹的智慧,这种本能引导 Achilles 以完美的判断力穿梭于每一场战斗中。 当 Patroclus 阵亡时,是 Xanthos 开口说话——由 Hera 亲自赐予声音——警告 Achilles 他的命运。但 Balios 保持沉默,他的智慧不是通过语言,而是通过行动表达出来;懂得何时冲锋,何时撤退;在马与英雄之间那种超越指令的完美默契中展现无遗。 ## 文档 - [架构](docs/ARCHITECTURE.md) - W-TinyLFU 内部原理、无锁设计、内存布局 - [性能](docs/PERFORMANCE.md) - 综合基准测试、命中率分析、可扩展性 - [GetOrLoad API](docs/GETORLOAD.md) - 缓存击穿防御、singleflight 模式、最佳实践 - [指标与可观测性](docs/METRICS.md) - OpenTelemetry 集成、Prometheus 查询、监控最佳实践 - [错误处理](docs/ERRORS.md) - 结构化错误代码和上下文 发现及生产安全保证 - [示例](examples/) - 丰富的使用示例 - [基准测试](benchmarks/) - 与流行库的性能比较 - [otel/README.md](otel/README.md) 和 [examples/otel-prometheus/](examples/otel-prometheus/) 用于包含 Grafana 仪表盘的完整设置。 ## 未来的增强功能(计划中) - 异步刷新(stale-while-revalidate 模式) - 持久化(从磁盘保存/加载) - 分布式缓存协调 - Write-through/write-behind 模式 ## 许可证 Balios 采用 [Mozilla Public License 2.0](./LICENSE.md) 授权。 Balios • AGILira 的一部分
Get/Set/Delete Operations] IFACE[MetricsCollector Interface
Thread-Safe API] NOOP[NoOpMetricsCollector
Zero Overhead Default
Compiler Inlined] end subgraph "Implementation Layer" OTEL[OpenTelemetry Collector
otel package
Professional Metrics] CUSTOM[Custom Collector
User Implementation
Domain-Specific] end subgraph "Observability Backends" PROM[Prometheus
Metrics Storage
Time-Series DB] JAEGER[Jaeger
Distributed Tracing
Performance Analysis] GRAFANA[Grafana
Visualization
Dashboards] end subgraph "Custom Integrations" DD[DataDog
APM Platform] CUSTOM_BACK[Custom Backend
Internal Tools
Domain-Specific] end %% Connections CACHE --> IFACE IFACE --> NOOP IFACE --> OTEL IFACE --> CUSTOM OTEL --> PROM OTEL --> JAEGER PROM --> GRAFANA CUSTOM --> DD CUSTOM --> CUSTOM_BACK %% Styling with Argus color scheme classDef core fill:#ecfdf5,stroke:#059669,stroke-width:2px classDef implementation fill:#f0f9ff,stroke:#0369a1,stroke-width:2px classDef observability fill:#fef3c7,stroke:#d97706,stroke-width:2px classDef custom fill:#f3e8ff,stroke:#7c3aed,stroke-width:2px class CACHE,IFACE,NOOP core class OTEL,CUSTOM implementation class PROM,JAEGER,GRAFANA observability class DD,CUSTOM_BACK custom ``` ### Logger 接口 ``` // Logger defines a minimal logging interface with zero overhead. // Implementations should use structured logging and be allocation-free. type Logger interface { // Debug logs a debug message with optional key-value pairs. Debug(msg string, keyvals ...interface{}) // Info logs an info message with optional key-value pairs. Info(msg string, keyvals ...interface{}) // Warn logs a warning message with optional key-value pairs. Warn(msg string, keyvals ...interface{}) // Error logs an error message with optional key-value pairs. Error(msg string, keyvals ...interface{}) } ``` **集成示例:** ``` import "log/slog" // Using standard library slog logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) cache := balios.New[string, User](balios.Config{ Size: 1000, Logger: logger, }) ``` 完整文档请参见 [指标与可观测性](docs/METRICS.md)。 ## Balios 背后的理念 Balios 和他的兄弟 Xanthos 是 Achilles 的不朽战马,由风神中最迅捷的 Zephyros 所生。它们不仅仅是快——它们是风本身的孩子,凡间马匹无法比拟。Balios 拥有超越任何马匹的智慧,这种本能引导 Achilles 以完美的判断力穿梭于每一场战斗中。 当 Patroclus 阵亡时,是 Xanthos 开口说话——由 Hera 亲自赐予声音——警告 Achilles 他的命运。但 Balios 保持沉默,他的智慧不是通过语言,而是通过行动表达出来;懂得何时冲锋,何时撤退;在马与英雄之间那种超越指令的完美默契中展现无遗。 ## 文档 - [架构](docs/ARCHITECTURE.md) - W-TinyLFU 内部原理、无锁设计、内存布局 - [性能](docs/PERFORMANCE.md) - 综合基准测试、命中率分析、可扩展性 - [GetOrLoad API](docs/GETORLOAD.md) - 缓存击穿防御、singleflight 模式、最佳实践 - [指标与可观测性](docs/METRICS.md) - OpenTelemetry 集成、Prometheus 查询、监控最佳实践 - [错误处理](docs/ERRORS.md) - 结构化错误代码和上下文 发现及生产安全保证 - [示例](examples/) - 丰富的使用示例 - [基准测试](benchmarks/) - 与流行库的性能比较 - [otel/README.md](otel/README.md) 和 [examples/otel-prometheus/](examples/otel-prometheus/) 用于包含 Grafana 仪表盘的完整设置。 ## 未来的增强功能(计划中) - 异步刷新(stale-while-revalidate 模式) - 持久化(从磁盘保存/加载) - 分布式缓存协调 - Write-through/write-behind 模式 ## 许可证 Balios 采用 [Mozilla Public License 2.0](./LICENSE.md) 授权。 Balios • AGILira 的一部分
标签:API集成, DNS解析, Go语言, Ristretto替代, TTL过期, W-TinyLFU算法, 上下文控制, 中间件, 代码安全, 内存缓存, 单飞模式, 可观测性, 后端开发, 开源项目, 无锁编程, 日志审计, 泛型, 漏洞枚举, 用户代理, 程序破解, 缓存淘汰策略, 自定义请求头, 防止缓存雪崩, 高吞吐量, 高命中率, 高并发