Golang Redis SetEX 方法:设置带过期时间的键值对
在 Golang 中使用 Redis 的 SetEX 方法可以通过以下步骤实现:
- 导入 Redis 客户端库
首先,需要导入 Redis 客户端库,可以使用 go-redis 库,它是一个 Redis 客户端库,提供了一些方便的方法来与 Redis 交互。
import "github.com/go-redis/redis/v8"
- 创建 Redis 客户端
在使用 Redis 客户端之前,需要创建一个 Redis 客户端实例。
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379", // Redis 服务器地址
Password: "", // Redis 认证密码
DB: 0, // Redis 数据库编号
})
- 使用 SetEX 方法设置键值对
使用 Redis 的 SetEX 方法可以设置一个带有过期时间的键值对,其中第一个参数为键,第二个参数为值,第三个参数为过期时间,单位为秒。
err := rdb.SetEX(ctx, "mykey", "myvalue", time.Second*10).Err()
if err != nil {
panic(err)
}
在上面的示例中,使用了 time.Second*10 作为过期时间,表示 10 秒后这个键值对会自动过期并被删除。
完整的示例代码如下:
package main
import (
"context"
"fmt"
"time"
"github.com/go-redis/redis/v8"
)
func main() {
// 创建 Redis 客户端实例
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
// 创建上下文对象
ctx := context.Background()
// 使用 SetEX 方法设置键值对
err := rdb.SetEX(ctx, "mykey", "myvalue", time.Second*10).Err()
if err != nil {
panic(err)
}
// 使用 Get 方法获取键值对
val, err := rdb.Get(ctx, "mykey").Result()
if err != nil {
panic(err)
}
fmt.Println("mykey:", val)
// 等待 10 秒钟,验证键值对是否过期
time.Sleep(time.Second * 10)
val, err = rdb.Get(ctx, "mykey").Result()
if err == redis.Nil {
fmt.Println("mykey does not exist")
} else if err != nil {
panic(err)
} else {
fmt.Println("mykey:", val)
}
}
原文地址: https://www.cveoy.top/t/topic/lDxx 著作权归作者所有。请勿转载和采集!