beego的Cache模塊

2023-11-21 10:45 更新

緩存模塊

beego 的 cache 模塊是用來做數據緩存的,設計思路來自于 database/sql,目前支持 file、memcache、memory 和 redis 四種引擎,安裝方式如下:

go get github.com/astaxie/beego/cache
如果你使用memcache 或者 redis 驅動就需要手工安裝引入包
go get -u github.com/astaxie/beego/cache/memcache
而且需要在使用的地方引入包
import _ "github.com/astaxie/beego/cache/memcache"

使用入門

首先引入包:

import (
    "github.com/astaxie/beego/cache"
)

然后初始化一個全局變量對象:

bm, err := cache.NewCache("memory", `{"interval":60}`)

然后我們就可以使用bm增刪改緩存:

bm.Put("astaxie", 1, 10*time.Second)
bm.Get("astaxie")
bm.IsExist("astaxie")
bm.Delete("astaxie")

引擎設置

目前支持四種不同的引擎,接下來分別介紹這四種引擎如何設置:

  • memory配置信息如下所示,配置的信息表示 GC 的時間,表示每個 60s 會進行一次過期清理: {"interval":60}
  • file配置信息如下所示,配置 CachePath 表示緩存的文件目錄,FileSuffix 表示文件后綴,DirectoryLevel 表示目錄層級,EmbedExpiry 表示過期設置 {"CachePath":"./cache","FileSuffix":".cache","DirectoryLevel":"2","EmbedExpiry":"120"}
  • redis配置信息如下所示,redis 采用了庫 redigo: {"key":"collectionName","conn":":6039","dbNum":"0","password":"thePassWord"} key: Redis collection 的名稱conn: Redis 連接信息dbNum: 連接 Redis 時的 DB 編號. 默認是0.password: 用于連接有密碼的 Redis 服務器.
  • memcache配置信息如下所示,memcache 采用了 vitess的庫,表示 memcache 的連接地址: {"conn":"127.0.0.1:11211"}

開發(fā)自己的引擎

cache 模塊采用了接口的方式實現,因此用戶可以很方便的實現接口,然后注冊就可以實現自己的 Cache 引擎:

type Cache interface {
    Get(key string) interface{}
    GetMulti(keys []string) []interface{}
    Put(key string, val interface{}, timeout time.Duration) error
    Delete(key string) error
    Incr(key string) error
    Decr(key string) error
    IsExist(key string) bool
    ClearAll() error
    StartAndGC(config string) error
}

用戶開發(fā)完畢在最后寫類似這樣的:

func init() {
    Register("myowncache", NewOwnCache())
}


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號