引言Cache实际上在项目很常见、常见的redis、memcached等等
为了减少代码修改,灵活切换缓存存储源
今天开始为期3天交大家,如何打造一款高效扩展性强的的Cache管理器
主要用来学习啊、共同进步
1、gocache设计理念全局缓存管理器
支持多个缓存源
interface定义接口,完美实现适配器设计模式
2、定义定义全局存储源
定义全局Cache管理器var Stores = make(map[string]StoreInterface)type Cache struct {
name string
store StoreInterface
}复制代码定义store接口type StoreInterface interface {
GetStoreName() string// 获取缓存
Get(key string) (interface{}, error)// 设置缓存带过期时间
Set(key string, value interface{}, time int) error// 设置永久缓存无过期时间
Forever(key string, value interface{}) error// 删除key
Delete(key string) error// 判断key是否存在
Has(key string) error// 全部清空
Clear() error// 获取缓存key的数量
Size() int// 获取expire
GetTTl(key string) (time.Duration, error)// 随机删除已过期key
GC()
}复制代码定义实例化Cache方法func New(name string) (*Cache, error) {
name = strings.ToLower(name)if store, ok := Stores[name]; ok {go store.GC()return &Cache{
name: name, //有点多余
store: store,
}, nil
} else {return nil, fmt.Errorf("Cache:unknown %s store please import", name)
}
}复制代码定义注册缓存源的方法 (忽略store名称大小写,都转成小写存储)func Register(name string, store StoreInterface) {if store == nil {
log.Panic("Cache: Register store is nil")
}
name = strings.ToLower(name)if _, ok := Stores[name]; ok {
log.Panic("Cache: Register store is exist")
}
Stores[name] = store
}复制代码定义Cache对外方法// 获取store名称func (c *Cache) GetStoreName() string {return c.store.GetStoreName()
}// 获取键值func (c *Cache) Get(key string) (interface