redis官网推荐redigo, 但同时go-redis也使用非常广泛, 并且go-redis封装得更好
因此这里研究下go-redis的使用方法
安装:
go get -u github.com/go-redis/redis
源码地址: https://github.com/go-redis/redis
文档地址:https://godoc.org/github.com/go-redis/redis
入门程序:
package main
import (
"github.com/go-redis/redis"
"fmt"
)
func ExampleClient() {
client := redis.NewClient(&redis.Options{
Addr: "192.168.137.18:6379",
Password: "", // no password set
DB: 0, // use default DB
})
pong, err := client.Ping().Result()
fmt.Println(pong, err)
err = client.Set("feekey", "examples", 0).Err()
if err != nil {
panic(err)
}
val, err := client.Get("feekey").Result()
if err != nil {
panic(err)
}
fmt.Println("feekey", val)
val2, err := client.Get("feekey2").Result()
if err == redis.Nil {
fmt.Println("feekey does not exist")
} else if err != nil {
panic(err)
} else {
fmt.Println("feekey", val2)
}
}
func main() {
ExampleClient()
}
输出:
PONG <nil>
feekey examples
feekey does not exist
用法相对比较简单, 与命令大致相同
// 不存在时设置
set, err := client.SetNX("feekey", "value", 10*time.Second).Result()
fmt.Println(set)
//直接执行一个命令
res, err := client.Do("set", "dotest", "testdo").Result()
fmt.Println(res)
// 在末尾添加
res2, err:= client.Append("feekey", "_add").Result()
fmt.Println(res2)
val, err = client.Get("feekey").Result()
if err != nil {
panic(err)
}
fmt.Println("feekey", val)
输出:
false
OK
12
feekey examples_add
其实redis提供的很多方法也是对执行命令接口的封装:
例如: append
源码定义:
func (c cmdable) Append(key, value string) *IntCmd {
cmd := NewIntCmd("append", key, value)
c(cmd)
return cmd
}
用户执行命令
例如:
Get := func(redisdb *redis.Client, key string) *redis.StringCmd {
cmd := redis.NewStringCmd("get", key)
redisdb.Process(cmd)
return cmd
}
v, err := Get(client, "key_does_not_exist").Result()
fmt.Printf("%q %s", v, err)
输出:
"" redis: nil
ps: client 为建立的连接client
使用NewStringCmd 封装get命令,获取字符串值
res, err := client.Do("set", "dotest", "testdo").Result()
fmt.Println(res)