golang redis 判断key是否存在
在 Go 语言中使用 Redis 的客户端库可以轻松地判断 Redis 中的键是否存在。以下是使用 go-redis 库的示例代码:
import (
"github.com/go-redis/redis"
)
func main() {
// 创建 Redis 客户端
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // Redis 无密码验证
DB: 0, // 使用默认数据库
})
// 判断键是否存在
exists, err := client.Exists("mykey").Result()
if err != nil {
panic(err)
}
if exists == 1 {
fmt.Println("键存在")
} else {
fmt.Println("键不存在")
}
}
在上面的代码中,我们使用 Redis 的 Exists 方法来判断键是否存在。该方法的返回值是一个整型数值,表示键在 Redis 中的存在状态,1 表示存在,0 表示不存在。如果出现错误,Exists 方法将返回一个非 nil 的错误对象,我们可以使用 panic 函数来处理该错误。
原文地址: https://www.cveoy.top/t/topic/vGJ 著作权归作者所有。请勿转载和采集!