链接: 完整示例
使用的包为
go get -u github.com/go-redis/redis/v8
初始化连接信息
var ctx context.Context
var rdx *redis.Client
func init() {
ctx = context.Background() // redis的连接信息需要用到上下文
rdx = redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379",
Password: "",
DB: 0,
})
_, err := rdx.Ping(ctx).Result()
if err != nil {
panic(err)
}
}
redis操作string
// set / get / strlen / append / del
func RdsString(ctx context.Context, rdx *redis.Client) {
key := "name"
value := "henry"
result, err := rdx.Set(ctx, key, value, -1).Result()
if err != nil {
fmt.Printf("set %s %s failed,error:%s\n", key, value, err)
return
}
fmt.Printf("set %s %s success,result: %s\n", key, value, result)
result, err = rdx.Get(ctx, key).Result()
if err != nil {
fmt.Printf("get key:%s failed,error:%s\n", key, err)
return
}
fmt.Printf("get %s success,result: %s\n", key, result)
i, err := rdx.StrLen(ctx, key).Result()
if err != nil {
fmt.Printf("strlen %s failed,error:%s\n", key, err)
return
}
fmt.Printf("strlen %s success,result: %d\n", key, i)
i2, err := rdx.Append(ctx, key, "W").Result()
if err != nil {
fmt.Printf("append %s %s failed,error:%s\n", key, "W", err)
return
}
fmt.Printf("append %s %s success,result:%d\n", key, "W", i2)
i3, err := rdx.Del(ctx, key).Result()
if err != nil {
fmt.Printf("del %s failed,error:%s\n", key, err)
return
}
fmt.Printf("del %s success,result:%d\n", key, i3)
}
GitHub上有String,Hash,List,Set,ZSet五种类型的常用命令操作