Go语言开发redis封装及简单使用详解
程序员文章站
2022-06-17 10:27:23
目录go redis 集合操作--sadd安装redigo带密码的redis操作批量添加无密码redis操作redis封装包参考go redis 集合操作--saddredis的go语言包,我们使用官...
go redis 集合操作--sadd
redis的go语言包,我们使用官方推荐的redigo,https://github.com/garyburd/redigo
安装redigo
$ go get github.com/garyburd/redigo
带密码的redis操作
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) }
无密码redis操作
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"))
redis封装包
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 }
参考
redigo
https://github.com/garyburd/redigo
redigo api reference
https://godoc.org/github.com/gomodule/redigo/redis
以上就是go语言开发redis封装及简单使用详解的详细内容,更多关于go语言开发redis封装及使用的资料请关注其它相关文章!
下一篇: 这个Java泛型不太正经