go-cache 是一個輕量級的基于內存的 key:value 儲存組件,類似于memcached,適用于在單機上運行的應用程序。它的主要優(yōu)點是,本質上是一個具有過期時間的線程安全map[string]interface{}。interface的結構決定了它不需要序列化?;趦却娴奶匦詻Q定了其不需要網絡傳輸其內容,因此就不存在網絡耗時。
主要具備如下功能:
線程安全,多 goroutine 并發(fā)安全訪問;
每個 item 可以單獨設置過期時間(或無過期時間);
自動定期清理過期的 item;
可以自定義清理回調函數(shù);
支持將緩存數(shù)據(jù)保存到文件,并從文件中恢復數(shù)據(jù)到內存。
項目地址:
文檔地址:
代碼中import引入路徑
import "github.com/patrickmn/go-cache"
基本使用
直接上代碼
package main
import (
"fmt"
"github.com/patrickmn/go-cache"
"time"
)
func main() {
// 初始化cache 默認過期時間設置為5*time.Minute,掃描過期key的間隔時間10*time.Minute
c := cache.New(5*time.Minute, 10*time.Minute)
// 設置為默認過期時間,即New時設置的時間5*time.Minute
c.Set("foo", "bar", cache.DefaultExpiration)
// 設置為不過期
c.Set("baz", 42, cache.NoExpiration)
// 設置指定過期時間為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)
}
// 驗證過期
<-time.After(5 * time.Second)
cacheRes, found := c.Get("cache")
if found {
fmt.Println(cacheRes)
} else {
fmt.Println("cache not found")
}
// 因為value是interface{}類型,所以如果需要存入的類型,需要斷言
var fooValue string
if x, ok := c.Get("foo"); ok {
fooValue = x.(string)
}
fmt.Println("fooValue:", fooValue)
//對于結構體,存儲一個指針,可以有一個更好的性能
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
}