0
点赞
收藏
分享

微信扫一扫

go开源cache2go项目蛤蟆笔记——简单使用-

西红柿上校 2022-08-16 阅读 31


1     下载开源

下载路径:https://github.com/muesli/cache2go

 

2     代码如下:

packagemain

import(
"fmt"
"time"

"cache2go-master"
)

//Keys&valuesincache2gocanbeoffarbitrarytypes,e.g.astruct.
typemyStructstruct{
text string
moreData[]byte
}

funcmain(){
//Accessinganewcachetableforthefirsttimewillcreateit.
cache:=cache2go.Cache("myCache")

//Wewillputanewiteminthecache.Itwillexpireafter
//notbeingaccessedviaValue(key)formorethan5seconds.
val:=myStruct{"Thisisatest!",[]byte{}}
cache.Add("someKey",5*time.Second,&val)

//Let'sretrievetheitemfromthecache.
res,err:=cache.Value("someKey")
iferr==nil{
fmt.Println("Foundvalueincache:",res.Data().(*myStruct).text)
}else{
fmt.Println("Errorretrievingvaluefromcache:",err)
}

//Waitfortheitemtoexpireincache.
time.Sleep(6*time.Second)
res,err=cache.Value("someKey")
iferr!=nil{
fmt.Println("Itemisnotcached(anymore).")
}

//Addanotheritemthatneverexpires.
cache.Add("someKey",0,&val)

//cache2gosupportsafewhandycallbacksandloadingmechanisms.
cache.SetAboutToDeleteItemCallback(func(e*cache2go.CacheItem){
fmt.Println("Deleting:",e.Key(),e.Data().(*myStruct).text,e.CreatedOn())
})

//Removetheitemfromthecache.
cache.Delete("someKey")

//Andwipetheentirecachetable.
cache.Flush()
}

3     执行如下

Found value in cache: Thisis a test!

Item is not cached(anymore).

Deleting: someKey This is a test! 2016-07-12 16:31:57.0289334 +0800 CST

 





举报

相关推荐

0 条评论