如今的redis大红大紫,并且不少应用场景都适合使用Reids来作缓存或者直接作存储,典型的如mysql前端缓存、手游里面的排行榜等。那么咱们怎样用golang来操做redis呢?html
熟悉redis的同窗,确定第一反应就是按照redis的协议,实现一个客户端与redis服务进行通讯便可。不熟悉redis的同窗,可能会说用cgo封装下官方的c客户端,妥妥的。是的,这两种方法均可以。既然redis这么火,那么这些工做有没有人作呢?答案是确定的。在redis的官方网站的客户端列表里就有众多golang的客户端。这个时候,可能你又要犯难了,我该用哪个呢?前端
熟悉reids的同窗都知道,官网加星星的客户端都是好客户端,就像棒子天上的星星同样神奇。但是坑爹的时,golang不一样于python有两个都是加星星的,这孰真孰假呢?python
具体我也了解,不过大概浏览了下源码,两者都是用golang实现了redis得协议,不过radix的源码感受不是那么清晰,相对来讲redigo的源码能够和命令对上,比较清晰,且redigo说其支持全部的redis命令。而后又网上搜了几篇文章1/文章2,最终仍是选择了redigo来尝试。mysql
conn , err := redis.DialTimeout("tcp", ":6379", 0, 1*time.Second, 1*time.Second)
参数的意义分别是网络类型“tcp”、地址和端口、链接超时、读超时和写超时时间。有了链接后。咱们就能够进行其余操做了。先看下db的大小git
size ,err := conn.Do("DBSIZE") fmt.Printf("size is %d \n",size) //输出: size is 8
在使用完后,经过调用 conn.Close()
关闭链接。github
对于最基本的命令使用,咱们统一调用:golang
Do(commandName string, args ...interface{}) (reply interface{}, err error)
这个接口,整个过程就和咱们使用redis命令同样。redis
咱们知道在redis的协议中,都是按照字符流的,那么Do函数是如何进行序列化的呢?下面是其转换规则:sql
Go Type Conversion []byte Sent as is string Sent as is int, int64 strconv.FormatInt(v) float64 strconv.FormatFloat(v, 'g', -1, 64) bool true -> "1", false -> "0" nil "" all other types fmt.Print(v)
其实就是byte数组和字符串不变,×××和浮点数转换成对应的字符串,bool用1或者0表示,nil为空字符串。数组
下面再看下执行后获得的结果返回值的类型:
Redis type Go type error redis.Error integer int64 simple string string bulk string []byte or nil if value not present. array []interface{} or nil if value not present.
如上表,redis中得类型会对应的转换成左边go中得类型,无需多解释。咱们来看几个例子:
conn , err := redis.DialTimeout("tcp", ":6379", 0, 1*time.Second, 1*time.Second) if err != nil { panic(err) } size ,err:= conn.Do("DBSIZE") fmt.Printf("size is %d \n",size) _,err = conn.Do("SET","user:user0",123) _,err = conn.Do("SET","user:user1",456) _,err = conn.Do("APPEND","user:user0",87) user0,err := redis.Int(conn.Do("GET","user:user0")) user1,err := redis.Int(conn.Do("GET","user:user1")) fmt.Printf("user0 is %d , user1 is %d \n",user0,user1) conn.Close()
从redis传回来得普通对象(×××、字符串、浮点数)。redis提供了类型转换函数供转换:
func Bool(reply interface{}, err error) (bool, error) func Bytes(reply interface{}, err error) ([]byte, error) func Float64(reply interface{}, err error) (float64, error) func Int(reply interface{}, err error) (int, error) func Int64(reply interface{}, err error) (int64, error) func String(reply interface{}, err error) (string, error) func Strings(reply interface{}, err error) ([]string, error) func Uint64(reply interface{}, err error) (uint64, error)
这里只是举了set和get命令。其余的例子能够参见redigo的conn_test.go