go-redis库的返回值
2019-06-08 本文已影响0人
golang推广大使
github.com/go-redis/redis
是go语言中封装的最便利使用的redis客户端,但是它的使用会给入门者一点小小的疑惑。具体看下面的例子
package main
import (
"fmt"
"github.com/go-redis/redis"
)
func main() {
cli := redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379",
})
res, err := cli.Ping().Result() //为什么要用result呢
fmt.Println(res, err)
}
上面例子中cli.Ping()
的执行不能直接得到结果,必须通过Result()
函数来获取。
cli.Ping()
函数实质上返回了一个*redis.StatusCmd
指针,这个类型有以下几个方法:
Name()
Args()
Err()
String()
Val()
-
Result()
在上面的例子中我们采用Result方法来获取返回的结果。虽然Val()
方法也能取得结果,但是它无法捕获错误,故而不为大家所采用。
当然这个库中执行其他命令返回的结果未必都有这些方法,另外即使方法名一样,返回的类型也不一样。
在上面的代码中加入下面几行
log.Printf("ping args %#v\n", cli.Ping().Args())
log.Printf("ping string %#v\n", cli.Ping().String())
log.Printf("ping err %#v\n", cli.Ping().Err())
log.Printf("ping name %#v\n", cli.Ping().Name())
log.Printf("ping val %#v\n", cli.Ping().Val())
res, err := cli.Ping().Result()
log.Printf("ping result ===%#v,%#v\n", res, err)
res, err = cli.Set("key", "vel", time.Second).Result()
log.Printf("set result ===%#v,%#v\n", res, err)
res, err = cli.Set("keyi", 10, time.Second).Result()
log.Printf("set result ===%#v,%#v\n", res, err)
res = cli.Incr("ikey").String()
log.Printf("incr string ===%#v,%#v\n", res, err)
resI, err := cli.Incr("ikey").Result()
log.Printf("incr result===%#v,%#v\n", resI, err)
cmd := cli.Incr("ikey")
i, err := cmd.Result()
log.Printf("incr result===%#v,%#v\n", i, err)
log.Printf("inc err==%#v", cmd.Err())
log.Printf("inc val==%#v", cmd.Val())
log.Printf("inc string==%#v", cmd.String())
log.Printf("inc args==%#v", cmd.Args())
setcmd := cli.Set("test", 1, time.Second)
res, err = setcmd.Result()
log.Printf("incr result===%#v,%#v\n", res, err)
log.Printf("inc err==%#v", setcmd.Err())
log.Printf("inc val==%#v", setcmd.Val())
log.Printf("inc string==%#v", setcmd.String())
log.Printf("inc args==%#v", setcmd.Args())
然后执行一下,可以得到下面的结果:
2019/06/08 ping args []interface {}{"ping"}
2019/06/08 ping string "ping: PONG"
2019/06/08 ping err <nil>
2019/06/08 ping name "ping"
2019/06/08 ping val "PONG"
2019/06/08 ping result ==="PONG",<nil>
2019/06/08 set result ==="OK",<nil>
2019/06/08 set result ==="OK",<nil>
2019/06/08 incr string ==="incr ikey: 18",<nil>
2019/06/08 incr result===19,<nil>
2019/06/08 incr result===20,<nil>
2019/06/08 inc err==<nil>
2019/06/08 inc val==20
2019/06/08 inc string=="incr ikey: 20"
2019/06/08 inc args==[]interface {}{"incr", "ikey"}
2019/06/08 incr result==="OK",<nil>
2019/06/08 inc err==<nil>
2019/06/08 inc val=="OK"
2019/06/08 inc string=="set test 1 ex 1: OK"
2019/06/08 inc args==[]interface {}{"set", "test", 1, "ex", 1}