tonglin0325的个人主页

go学习笔记——go-redis

官方文档

https://pkg.go.dev/github.com/go-redis/redis/v8#section-readme

添加依赖

1
2
3
go get github.com/go-redis/redis/v8
go get github.com/go-redis/redis/extra/redisotel/v8

初始化client

1
2
3
4
5
6
7
8
9
10
11
12
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})

client.AddHook(&redisotel.TracingHook{})
if err := client.Ping(context.Background()).Err(); err != nil {
logger.Error("redis connect failed, err:", zap.Any("err", err))
panic("failed to connect redis")
}

set key

1
2
3
4
5
err = rdb.Set(ctx, "key", 10, time.Hour).Err()
if err != nil {
fmt.Println(err)
}

get key

1
2
3
4
5
6
7
result := client.Get(ctx, "key")
str, err := result.Result()
if err != nil {
fmt.Println(err)
}
fmt.Println(str)

参考:Go语言操作Redis