go-cache 是一個(gè)輕量級(jí)的基于內(nèi)存的 key:value 儲(chǔ)存組件,類似于memcached,適用于在單機(jī)上運(yùn)行的應(yīng)用程序。它的主要優(yōu)點(diǎn)是,本質(zhì)上是一個(gè)具有過期時(shí)間的線程安全map[string]interface{}。interface的結(jié)構(gòu)決定了它不需要序列化?;趦?nèi)存的特性決定了其不需要網(wǎng)絡(luò)傳輸其內(nèi)容,因此就不存在網(wǎng)絡(luò)耗時(shí)。
主要具備如下功能:
線程安全,多 goroutine 并發(fā)安全訪問;
每個(gè) item 可以單獨(dú)設(shè)置過期時(shí)間(或無過期時(shí)間);
自動(dòng)定期清理過期的 item;
可以自定義清理回調(diào)函數(shù);
支持將緩存數(shù)據(jù)保存到文件,并從文件中恢復(fù)數(shù)據(jù)到內(nèi)存。
項(xiàng)目地址:
文檔地址:
代碼中import引入路徑
import "github.com/patrickmn/go-cache"
基本使用
直接上代碼
package main
import (
"fmt"
"github.com/patrickmn/go-cache"
"time"
)
func main() {
// 初始化cache 默認(rèn)過期時(shí)間設(shè)置為5*time.Minute,掃描過期key的間隔時(shí)間10*time.Minute
c := cache.New(5*time.Minute, 10*time.Minute)
// 設(shè)置為默認(rèn)過期時(shí)間,即New時(shí)設(shè)置的時(shí)間5*time.Minute
c.Set("foo", "bar", cache.DefaultExpiration)
// 設(shè)置為不過期
c.Set("baz", 42, cache.NoExpiration)
// 設(shè)置指定過期時(shí)間為100秒
c.Set("cache", 100, time.Second*3)
// Get the string associated with the key "foo" from the cache
foo, found := c.Get("foo")
if found {
fmt.Println(foo)
}
// 驗(yàn)證過期
<-time.After(5 * time.Second)
cacheRes, found := c.Get("cache")
if found {
fmt.Println(cacheRes)
} else {
fmt.Println("cache not found")
}
// 因?yàn)関alue是interface{}類型,所以如果需要存入的類型,需要斷言
var fooValue string
if x, ok := c.Get("foo"); ok {
fooValue = x.(string)
}
fmt.Println("fooValue:", fooValue)
//對(duì)于結(jié)構(gòu)體,存儲(chǔ)一個(gè)指針,可以有一個(gè)更好的性能
c.Set("MyStruct", &MyStruct{
Name: "gary",
Age: 18,
}, cache.DefaultExpiration)
if x, ok := c.Get("MyStruct"); ok {
res := x.(*MyStruct)
fmt.Println("MyStruct:", res)
}
// 刪除key
c.Delete("foo")
if fooRes, ok := c.Get("foo"); ok {
fmt.Println("after delete", fooRes)
} else {
fmt.Println("after delete not found foo")
}
}
type MyStruct struct {
Name string
Age int
}