- 您可以使用 go-redis 和 redi-go 作为工具连接 redis,然后选择您需要的数据类型。
示例:go-redis:
https://github.com/go-redis/redis
var ctx = context.Background()
func ExampleClient() {
//01 connect
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
err := rdb.Set(ctx, "key", "value", 0).Err()
if err != nil {
panic(err)
}
val, err := rdb.Get(ctx, "key").Result()
if err != nil {
panic(err)
}
fmt.Println("key", val)
}
- 结构到redis
类型用户结构{
用户 ID uint32
用户名字符串
}
var ctx = context.Background()
// Set set to redis as string
func Set() {
var u User
marshal, err := json.Marshal(&u)
if err != nil {
log.Println(err)
}
rdb.Set(ctx,"user",string(marshal),-1)
//-1 means no expiration time
}
// Get get from redis
func Get() {
var u User
bytes, err := rdb.Get(ctx, "user").Bytes()
if err != nil {
log.Println(err)
}
err = json.Unmarshal(bytes, &u)
if err != nil {
log.Println(err)
}
}