初始化缓存管理器
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
package cache_manager
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"code.yun.ink/pkg/cache_manager/manager"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// T必须实现IModel接口,提供TableName方法来获取表名,用于缓存键的生成
|
||||
type commonTableCache[T any] struct {
|
||||
tableName string
|
||||
cache manager.ICache
|
||||
ttl time.Duration
|
||||
*manager.EventManager[T] // 对外提供调用(自动缓存)
|
||||
cacheManager *manager.CacheManager[T] // 操作缓存管理器
|
||||
}
|
||||
|
||||
type IModel interface {
|
||||
TableName() string
|
||||
}
|
||||
|
||||
// newCommonCache 创建通用缓存结构
|
||||
// T 是实现了 IModel 接口的具体数据类型,实现了 IModel 接口的 TableName 方法来获取表名
|
||||
// cache 是缓存管理器实例,ttl 是缓存的过期时间,getId 是一个函数,用于从数据实例中提取唯一标识符(ID)
|
||||
// 适合于监听表数据变化并更新缓存的场景,提供了一个事件管理器来处理数据更新事件
|
||||
func NewCommonTableCache[T any](tx *gorm.DB, cache manager.ICache, ttl time.Duration, getId func(data *T) int64) (*commonTableCache[T], error) {
|
||||
var zero T
|
||||
|
||||
_, ok := any(&zero).(IModel) // 断言,确保 T 实现了 IModel 接口
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("type %T does not implement IModel", zero)
|
||||
}
|
||||
|
||||
tableName := any(&zero).(IModel).TableName()
|
||||
|
||||
o := &commonTableCache[T]{
|
||||
tableName: tableName,
|
||||
// cache: cache,
|
||||
ttl: ttl,
|
||||
}
|
||||
o.cacheManager = manager.NewCacheManager(tx, cache, tableName, getId)
|
||||
|
||||
o.EventManager = manager.NewEventManager(tx, o.ttl, o.cacheManager, getId)
|
||||
|
||||
// 注册事件监听器,用于处理数据更新和删除操作
|
||||
// global.EventRegister(o.tableName, o.cacheManager.Remove)
|
||||
|
||||
return o, nil
|
||||
}
|
||||
Reference in New Issue
Block a user