Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use redis in golang

Shulou Source: shulou.com Published: 2022-06-02 10:00:44 10月17日 Update

This article mainly explains "how to use redis in golang". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use redis in golang.

Introduction of github.com/gomodule/redigo/redis

Initialize redis connection func InitRedis () {password: = beego.AppConfig.String ("Redis::Password") redisHost: = beego.AppConfig.String ("Redis::Address") dataBase,_: = beego.AppConfig.Int ("Redis::DataBase") rc: = & redis.Pool {/ / maximum idle link MaxIdle: 10 / / maximum active link MaxActive: 10, / / maximum idle link waiting time IdleTimeout: 5 * time.Second, Dial: func () (redis.Conn, error) {r, err: = redis.Dial ("tcp", redisHost) ) if err! = nil {return nil, err} / / aws redis has no password 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 ()} commonly used get set del examples 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} use lua script example / * * counter * / 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 (1Powerscript) result,err: = luaScript.Do (redisConn,key,time,limitTimes) if err! = nil {beego.Error ("invokeLua script:", script,err)} return int (result. (int64))} so far I believe you have a deeper understanding of "the use of redis in golang", so you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Method usage maximum link content example free learning practical deeper interest practicality password common use simple operation time more friends activation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Shulou Tech Info macOS MariaDB Linux