Beego官方文档有连接Redis的说明,不过很简短。在这里,我把连接Redis的代码晒出来,跟大家分享一下。
package utils
import (
"encoding/json"
"github.com/astaxie/beego"
_ "github.com/astaxie/beego/cache/redis"
"github.com/astaxie/beego/cache"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
)
var Cache cache.Cache
func init() {
collectionName := beego.AppConfig.String("cache.collectionName")
conn := beego.AppConfig.String("cache.conn")
dbNum := beego.AppConfig.String("cache.dbNum")
//password := beego.AppConfig.String("cache.password")
// 设置配置参数
config := orm.Params{
"key": collectionName,
"conn": conn,
"dbNum": dbNum,
//"password": password,
}
configStr, err := json.Marshal(config)
logs.Debug(string(configStr))
if err != nil {
logs.Error("redis配置模型转换失败")
return
}
Cache,err = cache.NewCache("redis",string(configStr))
if err != nil {
logs.Error("redis初始化失败")
return
}
logs.Info("******************************************************************************")
logs.Info("********************************redis启动成功**********************************")
logs.Info("******************************************************************************")
}
这里有个坑
key的值为缓存数据在redis中的hashmap的表名,若不设置key的值,则默认为beecacheRedis。
Beego官方有Redis存取方法的说明,在这里就不一一赘述了。
不过大家要注意,此方法把数据存在一个hashmap里了,不是字符串,所以用的时候一定要想清楚了。
若是想用字符串的方式,可以用Redigo。
// tcp连接redis
rs, err := redis.Dial("tcp", host)
// 操作完后自动关闭
defer rs.Close()
// 操作redis时调用Do方法,第一个参数传入操作名称(字符串),然后根据不同操作传入key、value、数字等
// 返回2个参数,第一个为操作标识,成功则为1,失败则为0;第二个为错误信息
value, err := redis.String(rs.Do("GET", key))
if err != nil {
fmt.Println("fail")
}
若value的类型为int,则用redis.Int转换
若value的类型为string,则用redis.String转换
若value的类型为json,则用redis.Byte转换
// 存json数据
key := "aaa"
imap := map[string]string{"key1": "111", "key2": "222"}
// 将map转换成json数据
value, _ := json.Marshal(imap)
// 存入redis
n, err := rs.Do("SETNX", key, value)
if err != nil {
fmt.Println(err)
}
if n == int64(1) {
fmt.Println("success")
}
go 操作redis的一些坑
Beego 使用 Redis 存储字符串,Get 返回的是 interface{} 类型,必须要做这样的转换
redis里面set []byte 类型, get的时候用unmarshal反序列化得到struct 或者 []byte转换成string
bm, error := cache.NewCache("redis", `{"conn":"127.0.0.1:6379","key":"collectionName","dbNum":"0","password":""}`)
if error != nil {
fmt.Println("redis error:", error)
}
bm.Put("test", "hello", time.Second*100)
v := bm.Get("test")
fmt.Println("value:", string(v.([]byte)))