本篇內容主要講解“golang中redis的使用方法”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“golang中redis的使用方法”吧!
引入github.com/gomodule/redigo/redis
func InitRedis(){
password := beego.AppConfig.String("Redis::Password")
redisHost := beego.AppConfig.String("Redis::Address")
dataBase,_ := beego.AppConfig.Int("Redis::DataBase")
rc := &redis.Pool{
// 最大空閑鏈接
MaxIdle: 10,
// 最大激活鏈接
MaxActive: 10,
// 最大空閑鏈接等待時間
IdleTimeout: 5 * time.Second,
Dial: func() (redis.Conn, error) {
r, err := redis.Dial("tcp", redisHost,)
if err != nil {
return nil, err
}
//aws redis沒有密碼
if password != "" {
if _, err := r.Do("AUTH", password); err != nil {
r.Close()
return nil, err
}
}
r.Do("SELECT", dataBase)
return r, nil
},
}
redisConn = rc.Get()
}func SetKV(key string,value interface{},time int) (err error) {
_, err = redisConn.Do("SET", key, value, "EX", time)
if err != nil{
beego.Error("set key:",key,",value:",value,err)
}
return
}
func GetKV(key string) (value interface{}) {
value , err := redisConn.Do("GET", key)
if err != nil{
beego.Error("GetKV key:",key,err)
}
return value
}
func DelKey(key string) (err error) {
_, err = redisConn.Do("DEL", key)
if err != nil{
beego.Error("DelKey key:",key,err)
}
return
}/**
計數器
*/
func Counter(key string,time int ,limitTimes int) int {
script := " local num = redis.call('incr', KEYS[1]) \n" +
" if tonumber(num) == 1 then \n" +
"\t redis.call('expire', KEYS[1], ARGV[1]) \n" +
"\t return 1 \n" +
" elseif tonumber(num) > tonumber(ARGV[2]) then \n" +
"\t return 0 \n" +
" else \n" +
"\t return 1 \n" +
" end \n"
//result := invokeLua(1,lua,key,time,limitTimes)
luaScript := redis.NewScript(1,script)
result,err := luaScript.Do(redisConn,key,time,limitTimes)
if err != nil {
beego.Error("invokeLua script:",script,err)
}
return int( result.(int64) )
}到此,相信大家對“golang中redis的使用方法”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。