Documentation
¶
Overview ¶
Package cache 提供 Go-Cache 框架的全局缓存功能 (方案 G - Beego 融合版)
核心特性 ¶
- 全局管理器懒加载:无需手动传递 Manager
- 全局注解注册表:init() 自动注册,用户无感知
- 全局拦截器:方法调用时自动拦截,执行缓存逻辑
快速开始 ¶
1. 在 Service 方法上添加缓存注解:
// @cacheable(cache="products", key="#id", ttl="1h")
func (s *ProductService) GetProduct(id int64) (*model.Product, error) {
// 业务逻辑
}
2. 执行代码生成:
gocache scan ./service
3. 直接使用 (零配置):
func main() {
svc := cache.NewProductService()
product, err := svc.GetProduct(1)
}
高级用法 ¶
自定义缓存管理器 (可选):
func main() {
manager := core.NewCacheManager()
// 配置 Redis 后端...
cache.SetGlobalManager(manager)
svc := cache.NewProductService()
product, err := svc.GetProduct(1)
}
架构设计 ¶
方案 G 借鉴了 Beego 路由注解的设计:
- init() 自动注册所有注解到全局表
- GetGlobalManager() 懒加载创建管理器
- 代码生成器生成 NewXxxService() 函数
用户体验: "注解后直接使用",无需手动装饰或传递 Manager。
Index ¶
- func ClearGlobalAnnotations()
- func CloseGlobalManager()
- func GetAllAnnotations(typeName string) map[string]*proxy.CacheAnnotation
- func GetAllMetrics(cacheName string) map[string]interface{}
- func GetGlobalAnnotation(typeName, methodName string) *proxy.CacheAnnotation
- func GetGlobalManager() core.CacheManager
- func HasGlobalAnnotation(typeName, methodName string) bool
- func ListGlobalTypes() []string
- func RegisterGlobalAnnotation(typeName, methodName string, annotation *proxy.CacheAnnotation)
- func ResetGlobalManager()
- func SetGlobalManager(manager core.CacheManager)
- func UnregisterMetrics(cacheName string)
- type CacheOperation
- type GlobalInterceptor
- func (gi *GlobalInterceptor) GetManager() core.CacheManager
- func (gi *GlobalInterceptor) InterceptCacheEvict(typeName, methodName string, args []reflect.Value, ...) ([]reflect.Value, error)
- func (gi *GlobalInterceptor) InterceptCachePut(typeName, methodName string, args []reflect.Value, ...) ([]reflect.Value, error)
- func (gi *GlobalInterceptor) InterceptCacheable(typeName, methodName string, args []reflect.Value, ...) ([]reflect.Value, error)
- func (gi *GlobalInterceptor) SetManager(manager core.CacheManager)
- type MetricsCache
- func (m *MetricsCache) Close() error
- func (m *MetricsCache) Delete(ctx context.Context, key string) error
- func (m *MetricsCache) Get(ctx context.Context, key string) (interface{}, bool, error)
- func (m *MetricsCache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
- func (m *MetricsCache) Stats() *backend.CacheStats
- type MetricsCacheWithConfig
- func (m *MetricsCacheWithConfig) Close() error
- func (m *MetricsCacheWithConfig) Delete(ctx context.Context, key string) error
- func (m *MetricsCacheWithConfig) Get(ctx context.Context, key string) (interface{}, bool, error)
- func (m *MetricsCacheWithConfig) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
- func (m *MetricsCacheWithConfig) Stats() *backend.CacheStats
- type MetricsConfig
- type TraceConfig
- type TracedCache
- func (t *TracedCache) Close() error
- func (t *TracedCache) Delete(ctx context.Context, key string) error
- func (t *TracedCache) Get(ctx context.Context, key string) (interface{}, bool, error)
- func (t *TracedCache) GetTracer() trace.Tracer
- func (t *TracedCache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
- func (t *TracedCache) Stats() *backend.CacheStats
- type TracedCacheWithConfig
- func (t *TracedCacheWithConfig) Close() error
- func (t *TracedCacheWithConfig) Delete(ctx context.Context, key string) error
- func (t *TracedCacheWithConfig) Get(ctx context.Context, key string) (interface{}, bool, error)
- func (t *TracedCacheWithConfig) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
- func (t *TracedCacheWithConfig) Stats() *backend.CacheStats
- type TypeMismatchError
- type TypedCache
- func (t *TypedCache[T]) Close() error
- func (t *TypedCache[T]) Delete(ctx context.Context, key string) error
- func (t *TypedCache[T]) Get(ctx context.Context, key string) (T, bool, error)
- func (t *TypedCache[T]) GetOrSet(ctx context.Context, key string, fn func() (T, error), ttl time.Duration) (T, error)
- func (t *TypedCache[T]) Set(ctx context.Context, key string, value T, ttl time.Duration) error
- func (t *TypedCache[T]) Stats() *backend.CacheStats
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ClearGlobalAnnotations ¶
func ClearGlobalAnnotations()
ClearGlobalAnnotations 清空所有全局注解 (仅用于测试)
⚠️ 仅用于测试场景,生产环境不应使用。
func CloseGlobalManager ¶
func CloseGlobalManager()
CloseGlobalManager 关闭全局管理器 (应用退出时调用)
释放缓存资源,关闭后端连接 (如 Redis)。 应该在应用优雅关闭时调用。
使用示例:
func main() {
defer cache.CloseGlobalManager()
// 应用逻辑...
}
func GetAllAnnotations ¶
func GetAllAnnotations(typeName string) map[string]*proxy.CacheAnnotation
GetAllAnnotations 获取某类型的所有注解
返回指定类型的所有方法注解映射。 主要用于代码生成和调试。
func GetAllMetrics ¶
GetAllMetrics 获取所有指标的当前值(用于调试)
func GetGlobalAnnotation ¶
func GetGlobalAnnotation(typeName, methodName string) *proxy.CacheAnnotation
GetGlobalAnnotation 获取全局注解
根据类型名和方法名获取已注册的注解。 返回 nil 表示该方法没有缓存注解。
使用示例:
ann := cache.GetGlobalAnnotation("ProductService", "GetProduct")
if ann != nil {
// 该方法有缓存注解
}
func GetGlobalManager ¶
func GetGlobalManager() core.CacheManager
GetGlobalManager 获取全局管理器 (懒加载,线程安全)
这是方案 G 的核心:用户无需手动传递 Manager,框架自动管理。 懒加载确保只在第一次调用时创建,避免资源浪费。
使用示例:
func main() {
// 零配置:直接使用,Manager 自动创建
svc := cache.NewProductService()
// 或者自定义配置 (可选)
manager := core.NewCacheManager()
cache.SetGlobalManager(manager)
svc := cache.NewProductService()
}
func RegisterGlobalAnnotation ¶
func RegisterGlobalAnnotation(typeName, methodName string, annotation *proxy.CacheAnnotation)
RegisterGlobalAnnotation 注册全局注解 (供代码生成器调用)
这是方案 G 的核心机制:通过 init() 自动注册所有带注解的方法, 用户无需手动注册,实现"注解后直接使用"的体验。
此函数由 go generate 生成的代码调用,用户不应手动调用。
生成的代码示例:
// .cache-gen/auto_register.go
func init() {
cache.RegisterGlobalAnnotation("ProductService", "GetProduct", &proxy.CacheAnnotation{
Type: "cacheable",
CacheName: "products",
Key: "#id",
TTL: "1h",
})
}
func ResetGlobalManager ¶
func ResetGlobalManager()
ResetGlobalManager 重置全局管理器 (主要用于测试)
⚠️ 仅用于测试场景,生产环境不应使用。
func SetGlobalManager ¶
func SetGlobalManager(manager core.CacheManager)
SetGlobalManager 设置全局管理器 (可选,供高级用户)
99% 的用户不需要调用此函数。只有在需要自定义缓存配置 (如 Redis 后端、自定义 TTL、指标导出等) 时才使用。
注意:此函数应该在应用启动时调用一次,之后不应再修改。 如果在 NewXxxService() 之后调用,已创建的服务不会使用新 Manager。
使用示例:
func main() {
// 自定义 Manager (Redis 后端)
manager := core.NewCacheManager()
// 配置 Redis...
cache.SetGlobalManager(manager)
// 之后所有 NewXxxService() 都使用此 Manager
svc := cache.NewProductService()
}
Types ¶
type CacheOperation ¶
type CacheOperation string
CacheOperation 缓存操作类型
const ( OperationGet CacheOperation = "get" OperationSet CacheOperation = "set" OperationDelete CacheOperation = "delete" )
type GlobalInterceptor ¶
type GlobalInterceptor struct {
// contains filtered or unexported fields
}
GlobalInterceptor 全局缓存拦截器
这是方案 G 的核心执行引擎:在方法调用时拦截,根据注解执行缓存逻辑。 通过代码生成器在 init() 中自动注册,用户无感知。
func GetGlobalInterceptor ¶
func GetGlobalInterceptor() *GlobalInterceptor
GetGlobalInterceptor 获取全局拦截器单例
func (*GlobalInterceptor) GetManager ¶
func (gi *GlobalInterceptor) GetManager() core.CacheManager
GetManager 获取缓存管理器
func (*GlobalInterceptor) InterceptCacheEvict ¶
func (gi *GlobalInterceptor) InterceptCacheEvict( typeName, methodName string, args []reflect.Value, annotation *proxy.CacheAnnotation, originalFunc func() ([]reflect.Value, error), ) ([]reflect.Value, error)
InterceptCacheEvict 拦截 @cacheevict 方法
逻辑:根据 beforeInvocation 决定在方法执行前或后清除缓存。
func (*GlobalInterceptor) InterceptCachePut ¶
func (gi *GlobalInterceptor) InterceptCachePut( typeName, methodName string, args []reflect.Value, annotation *proxy.CacheAnnotation, originalFunc func() ([]reflect.Value, error), ) ([]reflect.Value, error)
InterceptCachePut 拦截 @cacheput 方法
逻辑:先执行原始方法,然后更新缓存。
func (*GlobalInterceptor) InterceptCacheable ¶
func (gi *GlobalInterceptor) InterceptCacheable( typeName, methodName string, args []reflect.Value, annotation *proxy.CacheAnnotation, originalFunc func() ([]reflect.Value, error), ) ([]reflect.Value, error)
InterceptCacheable 拦截 @cacheable 方法
核心逻辑: 1. 构建 SpEL 上下文 2. 生成缓存 Key 3. 查询缓存 (命中则返回) 4. 执行原始方法 5. 写入缓存
参数:
- typeName: 类型名 (如 "ProductService")
- methodName: 方法名 (如 "GetProduct")
- args: 方法参数
- annotation: 缓存注解
- originalFunc: 原始方法调用函数
返回: 方法执行结果
func (*GlobalInterceptor) SetManager ¶
func (gi *GlobalInterceptor) SetManager(manager core.CacheManager)
SetManager 设置缓存管理器
type MetricsCache ¶
type MetricsCache struct {
// contains filtered or unexported fields
}
MetricsCache 带 Prometheus 指标的缓存包装器
func NewMetricsCache ¶
func NewMetricsCache(backend backend.CacheBackend, cacheName string) *MetricsCache
NewMetricsCache 创建带指标的缓存包装器
func (*MetricsCache) Delete ¶
func (m *MetricsCache) Delete(ctx context.Context, key string) error
Delete 删除缓存值并记录指标
type MetricsCacheWithConfig ¶
type MetricsCacheWithConfig struct {
// contains filtered or unexported fields
}
MetricsCacheWithConfig 带配置的指标缓存
func NewMetricsCacheWithConfig ¶
func NewMetricsCacheWithConfig(backend backend.CacheBackend, name string, config *MetricsConfig) *MetricsCacheWithConfig
NewMetricsCacheWithConfig 创建带配置的指标缓存
func (*MetricsCacheWithConfig) Delete ¶
func (m *MetricsCacheWithConfig) Delete(ctx context.Context, key string) error
Delete 删除缓存值
func (*MetricsCacheWithConfig) Set ¶
func (m *MetricsCacheWithConfig) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
Set 设置缓存值
func (*MetricsCacheWithConfig) Stats ¶
func (m *MetricsCacheWithConfig) Stats() *backend.CacheStats
Stats 获取统计信息
type MetricsConfig ¶
type MetricsConfig struct {
// 是否启用指标
Enabled bool
// 是否记录详细指标(包括操作耗时)
EnableHistograms bool
// 缓存名称前缀
NamePrefix string
}
MetricsConfig 指标配置
type TraceConfig ¶
type TraceConfig struct {
// 是否启用追踪
Enabled bool
// 是否记录详细属性(包括缓存值)
Verbose bool
// 是否仅记录错误
ErrorsOnly bool
}
TraceConfig 追踪配置
type TracedCache ¶
type TracedCache struct {
// contains filtered or unexported fields
}
TracedCache 带 OpenTelemetry 追踪的缓存包装器 自动记录缓存操作的追踪信息
func NewTracedCache ¶
func NewTracedCache(backend backend.CacheBackend, cacheName string) *TracedCache
NewTracedCache 创建带追踪的缓存包装器 使用全局 OpenTelemetry TracerProvider
func NewTracedCacheWithTracer ¶
func NewTracedCacheWithTracer(backend backend.CacheBackend, tracer trace.Tracer, cacheName string) *TracedCache
NewTracedCacheWithTracer 使用自定义 Tracer 创建追踪缓存
func (*TracedCache) Delete ¶
func (t *TracedCache) Delete(ctx context.Context, key string) error
Delete 删除缓存值并记录追踪
func (*TracedCache) GetTracer ¶
func (t *TracedCache) GetTracer() trace.Tracer
GetTracer 获取 Tracer(用于自定义追踪)
type TracedCacheWithConfig ¶
type TracedCacheWithConfig struct {
// contains filtered or unexported fields
}
TracedCacheWithConfig 带配置的可追踪缓存
func NewTracedCacheWithConfig ¶
func NewTracedCacheWithConfig(backend backend.CacheBackend, name string, config *TraceConfig) *TracedCacheWithConfig
NewTracedCacheWithConfig 创建带配置的追踪缓存
func (*TracedCacheWithConfig) Delete ¶
func (t *TracedCacheWithConfig) Delete(ctx context.Context, key string) error
Delete 删除缓存值
func (*TracedCacheWithConfig) Set ¶
func (t *TracedCacheWithConfig) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
Set 设置缓存值
func (*TracedCacheWithConfig) Stats ¶
func (t *TracedCacheWithConfig) Stats() *backend.CacheStats
Stats 获取统计信息
type TypeMismatchError ¶
type TypeMismatchError struct {
// contains filtered or unexported fields
}
TypeMismatchError 类型不匹配错误
func (*TypeMismatchError) Error ¶
func (e *TypeMismatchError) Error() string
type TypedCache ¶
type TypedCache[T any] struct { // contains filtered or unexported fields }
TypedCache 泛型缓存适配器(类型安全) 提供类型安全的缓存访问,避免类型断言
func NewTypedCache ¶
func NewTypedCache[T any](backend backend.CacheBackend) *TypedCache[T]
NewTypedCache 创建泛型缓存适配器 适用于需要类型安全的场景
func (*TypedCache[T]) Delete ¶
func (t *TypedCache[T]) Delete(ctx context.Context, key string) error
Delete 删除缓存值
func (*TypedCache[T]) GetOrSet ¶
func (t *TypedCache[T]) GetOrSet(ctx context.Context, key string, fn func() (T, error), ttl time.Duration) (T, error)
GetOrSet 获取或设置缓存值(原子操作)