github.com/patrickmn/go-cache go-cache是一款类似于memached 的key/value 缓存软件。它比较适用于单机执行的应用程序。go-cache实质上就是拥有过期时间并且线程安全的map,可以被多个goroutine安全访问。并别代码量也相对较少,今天我们一起对go-cache代码包进行学习。
我们这里先上用法说明
package main
import (
"log"
"time"
"github.com/patrickmn/go-cache"
)
func main(){
c := cache.New(30*time.Second, 10*time.Second)//new 一个cache,并且设置默认过期时间30s和清理周期10s。
value, found := c.Get("test") //从cache中读取key 为test的value。
if found {
log.Println("found:", value)
} else {
log.Println("not found")
}
c.Set("test", "test value", cache.DefaultExpiration) //向cache中写入key/value数据,并且设置过期时间为默认,这里的默认就是我们在new cache时设置怼默认过期时间(30s)
value, found := c.Get("test")//从cache中读取key 为test的value。显然我们在这里就能读取到数据了
if found {