golang中redis的使用方法
更新:HHH   时间:2023-1-7


本篇内容主要讲解“golang中redis的使用方法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“golang中redis的使用方法”吧!

引入github.com/gomodule/redigo/redis

初始化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()
}

常用get set del示例

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
}

使用lua脚本示例

/**
计数器
 */
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的使用方法”有了更深的了解,不妨来实际操作一番吧!这里是天达云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

返回大数据教程...