本篇内容主要讲解“怎么封装使用Go语言开发的redis”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么封装使用Go语言开发的redis”吧!
redis的go语言包,我们使用官方推荐的redigo,https://github.com/garyburd/redigo
$ go get github.com/garyburd/redigo
package main import ( "log" "github.com/garyburd/redigo/redis" ) func main() { server := "127.0.0.1:6379" option := redis.DialPassword("123456") c, err := redis.Dial("tcp", server, option) if err != nil { log.Println("connect server failed:", err) return } defer c.Close() v, err := redis.Int64(c.Do("SADD", "myset", "10.8.37.98")) if err != nil { log.Println("SADD failed:", err) return } log.Println("value:", v) }
package main import ( "log" "github.com/garyburd/redigo/redis" ) func main() { server := "127.0.0.1:6379" option := redis.DialPassword("123456") c, err := redis.Dial("tcp", server, option) if err != nil { log.Println("connect server failed:", err) return } defer c.Close() setKey := "myset" args := []interface{}{setKey} args = append(args, "10.1") args = append(args, "10.2") v, err := redis.Int64(c.Do("SADD", args...)) if err != nil { log.Println("SADD failed:", err) return } log.Println("value:", v) }
package main import ( "fmt" "github.com/gomodule/redigo/redis" ) func main() { c, err := redis.Dial("tcp", "127.0.0.1:6379") if err != nil { fmt.Println(err) return } defer c.Close() c.Do("SET", "hello", "world") s, err := redis.String(c.Do("GET", "hello"))
package redis import ( "autumn/tools/cfg" "fmt" "github.com/gomodule/redigo/redis" "log" ) var REDIS redis.Conn func InitRedis() { REDIS = redis_connect("default") } func CloseRedis() { REDIS.Close() } func redis_connect(project string) redis.Conn { server := fmt.Sprintf("%s:%s", cfg.Get("redis", project+".host").String(), cfg.Get("redis", project+".port").String()) var err error option := redis.DialPassword(cfg.Get("redis", project+".passwd").String()) c, err := redis.Dial("tcp", server, option) if err != nil { log.Fatal("[GIN-MYSQL(" + project + ")] connect to redis error:" + err.Error()) } log.Println("[GIN-Redis(" + project + ")] connected success") return c }
到此,相信大家对“怎么封装使用Go语言开发的redis”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。