簡單好用的緩存庫 gcache
1.前言
開發(fā)時(shí),如果你需要對數(shù)據(jù)進(jìn)行臨時(shí)緩存,按照一定的淘汰策略,那么gcache你一定不要錯(cuò)過。gcache golang的緩存庫。它支持可擴(kuò)展的Cache,可以選擇 LFU,LRU、ARC等淘汰算法。
2.特性
gcache 有很多特性:
支持過期淘汰算法Cache,比如 LFU, LRU和ARC Goroutine安全 支持事件處理程序,淘汰、清除、添加 (可選) 自動加載緩存,如果它不存在 (可選) … ….
更多功能特性請查看:gcache (文末鏈接點(diǎn)擊可直接跳轉(zhuǎn)哦~)
3.快速安裝
直接get即可使用。
$ go get -u https://github.com/bluele/gcache
4.簡單舉例
package main
import (
"github.com/bluele/gcache"
"fmt"
)
func main() {
gc := gcache.New(20).
LRU().
Build()
gc.Set("key", "ok")
value, err := gc.Get("key")
if err != nil {
panic(err)
}
fmt.Println("Get:", value)
}
執(zhí)行,控制臺輸出如下:
Get: ok
5.設(shè)置淘汰時(shí)間舉例
package main
import (
"github.com/bluele/gcache"
"fmt"
"time"
)
func main() {
gc := gcache.New(20).
LRU().
Build()
gc.SetWithExpire("key", "ok", time.Second*10)
value, _ := gc.Get("key")
fmt.Println("Get:", value)
// Wait for value to expire
time.Sleep(time.Second*10)
value, err := gc.Get("key")
if err != nil {
panic(err)
}
fmt.Println("Get:", value)
}
執(zhí)行,控制臺輸出如下:
Get: ok
panic: Key not found.
goroutine 1 [running]:
main.main()
/Users/laocheng/work/code/market-data-backend/utils/t/2.go:22 +0x21b
exit status 2
6.其他算法舉例
6.1 最不經(jīng)常使用(LFU)
func main() {
// size: 10
gc := gcache.New(10).
LFU().
Build()
gc.Set("key", "value")
}
6.2 最近使用最少的(LRU)
func main() {
// size: 10
gc := gcache.New(10).
LRU().
Build()
gc.Set("key", "value")
}
6.3 自適應(yīng)替換緩存(ARC) 在LRU和LFU之間不斷平衡,以提高綜合結(jié)果。
func main() {
// size: 10
gc := gcache.New(10).
ARC().
Build()
gc.Set("key", "value")
}
7.添加hanlder使用
func main() {
gc := gcache.New(2).
AddedFunc(func(key, value interface{}) {
fmt.Println("added key:", key)
}).
Build()
for i := 0; i < 3; i++ {
gc.Set(i, i*i)
}
}
執(zhí)行,控制臺輸出如下:
added key: 0
added key: 1
added key: 2
可以在set時(shí)候做一些額外的處理。
8.總結(jié)
gcache 是一個(gè)非常簡單,又好用的緩存庫,它支持LFU,LRU、ARC等淘汰算法。如果你在開發(fā)時(shí)候有這方面的需求,不妨試試看,相信一定會喜歡上的!
參考資料:
gcache
往期推薦
想要了解Go更多內(nèi)容,歡迎掃描下方?? 關(guān)注 公眾號,回復(fù)關(guān)鍵詞 [實(shí)戰(zhàn)群] ,就有機(jī)會進(jìn)群和我們進(jìn)行交流
分享、在看與點(diǎn)贊,至少我要擁有一個(gè)叭~

評論
圖片
表情


