前言
在我基于 beego 寫博客的時候遇到一個很奇怪的問題铸本,那就是在使用 Memory
Cache 類型緩存的時候,緩存不生效很是奇怪遵堵,但是使用 redis
就沒問題箱玷。由于時間問題我就沒有深究,畢竟那時候?qū)嶋H上也會選用Memory
做緩存的陌宿。所以就放了下來锡足,直到今天在群里有人問了同樣的問題。我決定去研究一下這個坑壳坪。
我們先來看一個例子
Set Cache 代碼:
var (
urlcache cache.Cache
)
func init() {
urlcache, _ = cache.NewCache("memory", `{"interval":10}`)
}
func (this *SetController) Get() {
urlcache.Put("test", "test result sada", 60)
}
Get Cache 代碼:
func (this *GetController) Get() {
result := urlcache.Get("test")
this.Data["json"] = result
this.ServeJSON()
}
先賣個關(guān)子舶得,先別往下看,思考一下你們覺得輸出的結(jié)果是什么爽蝴?
沒錯沐批,結(jié)果是:
null
那么我們再看一下例子:
Set Cache 代碼:
var (
urlcache cache.Cache
)
func init() {
urlcache, _ = cache.NewCache("memory", `{"interval":10}`)
}
func (this *SetController) Get() {
urlcache.Put("test", "test result sada", 0)
}
Get Cache 代碼:
func (this *GetController) Get() {
result := urlcache.Get("test")
this.Data["json"] = result
this.ServeJSON()
}
再來猜一下這回結(jié)果是什么?
大家可能都知道了蝎亚,結(jié)果:
test result sada
那糾究竟是為什么會這樣呢九孩?真相只有一個!
原來這個 Put
的第三個參數(shù)颖对,設(shè)置內(nèi)存的 GC 的時間單位是 time.Duration
也就是我們說的納秒捻撑,所以我們在直接設(shè)置這個時間的時候經(jīng)常忽略單位只寫了個數(shù)字磨隘,所以最后我們回頭取緩存的時候缤底,緩存早已經(jīng)過期的了。
這個事情告訴我們看文檔一定要細(xì)心番捂。我貼一下文檔以及 Cache
源碼:
官方文檔給的接口:
type Cache interface {
Get(key string) interface{}
GetMulti(keys []string) []interface{}
Put(key string, val interface{}, timeout time.Duration) error
Delete(key string) error
Incr(key string) error
Decr(key string) error
IsExist(key string) bool
ClearAll() error
StartAndGC(config string) error
}
memory.go
源碼:
// Put cache to memory.
// if lifespan is 0, it will be forever till restart.
func (bc *MemoryCache) Put(name string, value interface{}, lifespan time.Duration) error {
bc.Lock()
defer bc.Unlock()
bc.items[name] = &MemoryItem{
val: value,
createdTime: time.Now(),
lifespan: lifespan,
}
return nil
}
歡迎各位朋友留言評論一起學(xué)習(xí)交流个唧。