beego源码解析之cache
Posted better_hui
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了beego源码解析之cache相关的知识,希望对你有一定的参考价值。
目录
cache目前支持memory、file、redis、memcache,这种引擎模式,下文基于memory引擎
使用
import ( "github.com/astaxie/beego/cache" ) bm, err := cache.NewCache("memory", `{"interval":60}`) bm.Put("astaxie", 1, 10*time.Second)
cache顶级接口
type Cache interface { // get cached value by key. Get(key string) interface{} // GetMulti is a batch version of Get. GetMulti(keys []string) []interface{} // set cached value with key and expire time. Put(key string, val interface{}, timeout time.Duration) error // delete cached value by key. Delete(key string) error // increase cached int value by key, as a counter. Incr(key string) error // decrease cached int value by key, as a counter. Decr(key string) error // check if cached value exists or not. IsExist(key string) bool // clear all cache. ClearAll() error // start gc routine based on config string settings. StartAndGC(config string) error } //基于内存的cache实现 type MemoryCache struct { sync.RWMutex dur time.Duration items map[string]*MemoryItem Every int // run an expiration check Every clock time }
register
注册的方法,可以自定义缓存的实现。
//定义一个函数类型,自定义的缓存需要实现这样的函数 给注册函数 type Instance func() Cache //缓存adapter集合 var adapters = make(map[string]Instance) //缓存adapter注册 func Register(name string, adapter Instance) { if adapter == nil { panic("cache: Register adapter is nil") } if _, ok := adapters[name]; ok { panic("cache: Register called twice for adapter " + name) } adapters[name] = adapter }
实例化
func NewCache(adapterName, config string) (adapter Cache, err error) { //根据类型获取转换器 , 这个转换器就是上文 type Instance func() Cache ,这个的具体实现,其返回一个cache instanceFunc, ok := adapters[adapterName] if !ok { err = fmt.Errorf("cache: unknown adapter name %q (forgot to import?)", adapterName) return } adapter = instanceFunc() //开启缓存和GC err = adapter.StartAndGC(config) if err != nil { adapter = nil } return } func (bc *MemoryCache) StartAndGC(config string) error { var cf map[string]int json.Unmarshal([]byte(config), &cf) if _, ok := cf["interval"]; !ok { cf = make(map[string]int) cf["interval"] = DefaultEvery } dur := time.Duration(cf["interval"]) * time.Second bc.Every = cf["interval"] bc.dur = dur go bc.vaccuum() return nil }
以上是关于beego源码解析之cache的主要内容,如果未能解决你的问题,请参考以下文章