用redis来作为cach其实官网已经很详细了https://beego.me/docs/module/cache.md,只是我一般喜欢封装成通用方法
直接上代码吧 redis.go作为通用工具类:
package redis
import (
"fmt"
"time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/cache"
_ "github.com/astaxie/beego/cache/redis"
_ "github.com/gomodule/redigo/redis"
)
var redisCache cache.Cache
func init() {
redisHost := beego.AppConfig.String("redis::address")
dataBase := beego.AppConfig.String("redis::database")
password := beego.AppConfig.String("redis::password")
redisKey := beego.AppConfig.String("redis::key")
config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`, redisKey, redisHost, dataBase, password)
var err error
redisCache, err = cache.NewCache("redis", config)
if err != nil || redisCache == nil {
errMsg := "failed to init redis"
beego.Error(errMsg, err)
panic(errMsg)
}
}
func SetStr(key, value string, time time.Duration) (err error) {
err = redisCache.Put(key, value, time)
if err != nil {
beego.Error("set key:", key, ",value:", value, err)
}
return
}
func GetStr(key string) (value string) {
v := redisCache.Get(key)
value = string(v.([]byte)) //这里的转换很重要,Get返回的是interface
return
}
func DelKey(key string) (err error) {
err = redisCache.Delete(key)
return
}
使用的时候需要修改配置文件app.conf
[redis]
address=localhost:6379
database=0
password=""
key="demo"
我一般习惯用字符串,所以上面redis封装的也是string, 如果是对象就用json 序列化和返序列化,使用示例:
func (c *MainController) Get() {
//声明对象
type TokenView struct {
Token string
LoginTime string
LoginIp string
}
//实例化
t := TokenView{
Token: string(xid.New().String()),
LoginTime: string(time.Now().Format("2006-01-02 15:04:05")),
LoginIp: strings.TrimSpace(c.Ctx.Input.IP()),
}
//json序列化
str, err := json.Marshal(t)
if err != nil {
fmt.Print(err)
}
///redis保存
redis.SetStr("test", string(str), time.Minute*time.Duration(10))
//redis获取
v := redis.GetStr("test")
fmt.Println(v)
//json反序列化
var obj TokenView
json.Unmarshal([]byte(v), &obj)
fmt.Println(obj.Token)
c.TplName = "index.html"
}
必要的包还是 要引入的:
import (
"demo/redis"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/astaxie/beego"
"github.com/rs/xid"
)