golang-redis keys 的操作
本文来自于 github.com/go-redis/redis/v9 的自带的测试代码 commands_test
1、keys
1. 删除
Del(ctx context.Context, keys ...string) 返回删除个数
// 删除 Del,使用 del 删除 大key 会造成长时间的阻塞,甚至崩溃 // 大key 是指 key 的 value 是个庞然大物,如 Hashes, Sorted Sets, Lists, Sets // 日积月累之后,会变得非常大,直接使用 del 进行删除,会导致长时间的阻塞,甚至崩溃 // Redis 是单线程的,单个命令执行时间长了会阻塞其他命令,容易引起雪崩 // 非字符串的 bigkey , 不要使用 del 删除。 可以使用 unlink
Unlink(ctx context.Context, keys ...string) 返回删除个数
// 删除 Unlink 将实际的键和键空间断开连接,实际的删除将会异步进行。不会阻塞 // 场景 删除 大 key 的时候使用,并且占用空间积累速度别是特别快 // 工作原理: // 1、把所有的命名空间 key 删除,立即返回,不阻塞 // 2、后台线程执行真正的释放空间
2、Dump(ctx context.Context, key string) 序列化
// 序列化给定的 key 为字节 Dump , key 需要在 redis 中存在
dump := client.Dump(ctx, "key")
3、Exists(ctx context.Context, keys ...string) 返回 key 存在的个数
n, err = client.Exists(ctx, "key1", "key2").Result() // 存在的个数
4、Expire(ctx context.Context, key string, expiration time.Duration) 给 key 设置过期时间
返回 bool 值
1 | expire := client.Expire(ctx, "key" , 10*time.Second) |
5、TTL(ctx context.Context, key string) 查看过期时间
1 2 3 | ttl := client.TTL(ctx, "key" ) Expect(ttl.Err()).NotTo(HaveOccurred()) Expect(ttl.Val()).To(Equal(10 * time.Second))<br><br>set = client.Set(ctx, "key" , "Hello World" , 0)<br>Expect(set.Val()).To(Equal( "OK" ))<br><br>ttl = client.TTL(ctx, "key" )<br>Expect(ttl.Val()).To(Equal(time.Duration(-1))) // 永不过期<br><br>ttl = client.TTL(ctx, "nonexistent_key")<br>Expect(ttl.Val()).To(Equal(time.Duration(-2))) // 不存在 |
6、ExpireAt(ctx context.Context, key string, tm time.Time) 设置过期时间
expireAt := client.ExpireAt(ctx, "key", time.Now().Add(-time.Hour)) // 立即过期 Expect(expireAt.Err()).NotTo(HaveOccurred()) Expect(expireAt.Val()).To(Equal(true))
7、Keys(ctx context.Context, pattern string) 获取匹配的 key
mset := client.MSet(ctx, "one", "1", "two", "2", "three", "3", "four", "4")
Expect(mset.Err()).NotTo(HaveOccurred())
Expect(mset.Val()).To(Equal("OK"))
keys := client.Keys(ctx, "*o*") // key 中包含 a 的
Expect(keys.Err()).NotTo(HaveOccurred())
Expect(keys.Val()).To(ConsistOf([]string{"four", "one", "two"}))
keys = client.Keys(ctx, "t??") // key 中以 t 打头的且长度为 3
Expect(keys.Err()).NotTo(HaveOccurred())
Expect(keys.Val()).To(Equal([]string{"two"}))
keys = client.Keys(ctx, "*") // 所有的
Expect(keys.Err()).NotTo(HaveOccurred())
Expect(keys.Val()).To(ConsistOf([]string{"four", "one", "three", "two"}))
8、Migrate(ctx context.Context, host, port, key string, db int, timeout time.Duration)
命令用于将 KEY 原子性地从当前 Redis 实例传送到目标实例的指定数据库上。如果传送成功, KEY 保证会出现在目标实例上,而当前实例上的 KEY 会被删除。
这个命令是一个原子操作,它在执行的时候会阻塞进行迁移的两个实例,直到以下任意结果发生:迁移成功,迁移失败,等到超时。
migrate := client.Migrate(ctx, "localhost", redisSecondaryPort, "key", 0, 0)
Expect(migrate.Err()).NotTo(HaveOccurred())
Expect(migrate.Val()).To(Equal("NOKEY"))
set := client.Set(ctx, "key", "hello", 0)
Expect(set.Err()).NotTo(HaveOccurred())
Expect(set.Val()).To(Equal("OK"))
migrate = client.Migrate(ctx, "localhost", redisSecondaryPort, "key", 0, 0)
Expect(migrate.Err()).To(MatchError("IOERR error or timeout writing to target instance"))
Expect(migrate.Val()).To(Equal(""))
9、Move(ctx context.Context, key string, db int)
Redis Move 命令用于将当前 Redis 数据库的 KEY 移动到给定的数据库 db 当中。
10、ObjectRefCount(ctx context.Context, key string)
11、Persist(ctx context.Context, key string) 删除key1过期时间,以后一直存在
persist := client.Persist(ctx, "key") Expect(persist.Err()).NotTo(HaveOccurred()) Expect(persist.Val()).To(Equal(true)) ttl = client.TTL(ctx, "key") Expect(ttl.Err()).NotTo(HaveOccurred()) Expect(ttl.Val() < 0).To(Equal(true))
12、PExpire(ctx context.Context, key string, expiration time.Duration)
Redis PEXPIRE 命令和 EXPIRE 命令的作用类似,但是它以毫秒为单位设置 key 的生存时间,
而不像 EXPIRE 命令那样,以秒为单位。
expiration := 900 * time.Millisecond
pexpire := client.PExpire(ctx, "key", expiration)
Expect(pexpire.Err()).NotTo(HaveOccurred())
Expect(pexpire.Val()).To(Equal(true))
13、PTTL(ctx context.Context, key string)
Pttl 命令以毫秒为单位返回 key 的剩余过期时间
pttl := client.PTTL(ctx, "key")
Expect(pttl.Val()).To(BeNumerically("~", expiration, 100*time.Millisecond))
14、PExpireAt(ctx context.Context, key string, tm time.Time)
PEXPIREAT 命令用于设置 key 的过期时间,以毫秒计。key 过期后将不再可用。
set := client.Set(ctx, "key", "Hello", 0)
Expect(set.Err()).NotTo(HaveOccurred())
Expect(set.Val()).To(Equal("OK"))
expiration := 900 * time.Millisecond
pexpireat := client.PExpireAt(ctx, "key", time.Now().Add(expiration))
Expect(pexpireat.Err()).NotTo(HaveOccurred())
Expect(pexpireat.Val()).To(Equal(true))
ttl := client.TTL(ctx, "key")
Expect(ttl.Err()).NotTo(HaveOccurred())
Expect(ttl.Val()).To(Equal(time.Second))
pttl := client.PTTL(ctx, "key")
Expect(pttl.Err()).NotTo(HaveOccurred())
Expect(pttl.Val()).To(BeNumerically("~", expiration, 100*time.Millisecond))
15、RandomKey(ctx context.Context)
令从当前数据库中随机返回一个 key
randomKey = client.RandomKey(ctx)
Expect(randomKey.Err()).NotTo(HaveOccurred())
Expect(randomKey.Val()).To(Equal("key"))
16、Rename(ctx context.Context, key, newkey string)
Rename 命令用于修改 key 的名称 。
set := client.Set(ctx, "key", "hello", 0)
Expect(set.Err()).NotTo(HaveOccurred())
Expect(set.Val()).To(Equal("OK"))
status := client.Rename(ctx, "key", "key1")
Expect(status.Err()).NotTo(HaveOccurred())
Expect(status.Val()).To(Equal("OK"))
get := client.Get(ctx, "key1")
Expect(get.Err()).NotTo(HaveOccurred())
Expect(get.Val()).To(Equal("hello"))
17、RenameNX(ctx context.Context, key, newkey string)
命令用于在新的 key 不存在时修改 key 的名称
set := client.Set(ctx, "key", "hello", 0)
Expect(set.Err()).NotTo(HaveOccurred())
Expect(set.Val()).To(Equal("OK"))
renameNX := client.RenameNX(ctx, "key", "key1")
Expect(renameNX.Err()).NotTo(HaveOccurred())
Expect(renameNX.Val()).To(Equal(true))
get := client.Get(ctx, "key1")
Expect(get.Err()).NotTo(HaveOccurred())
Expect(get.Val()).To(Equal("hello"))
18、Sort(ctx context.Context, key string, sort *Sort)
这是最简单的情况,没有任何选项对集合自身元素排序并返回排序结果,默认为value升序。
size, err := client.LPush(ctx, "list", "1").Result()
Expect(err).NotTo(HaveOccurred())
Expect(size).To(Equal(int64(1)))
size, err = client.LPush(ctx, "list", "3").Result()
Expect(err).NotTo(HaveOccurred())
Expect(size).To(Equal(int64(2)))
size, err = client.LPush(ctx, "list", "2").Result()
Expect(err).NotTo(HaveOccurred())
Expect(size).To(Equal(int64(3)))
els, err := client.Sort(ctx, "list", &redis.Sort{
Offset: 0,
Count: 2,
Order: "ASC",
}).Result()
Expect(err).NotTo(HaveOccurred())
Expect(els).To(Equal([]string{"1", "2"}))
19、type
返回 key 的数据类型,数据类型有: none (key不存在) string (字符串) list (列表) set (集合) zset (有序集) hash (哈希表)
set := client.Set(ctx, "key", "hello", 0)
Expect(set.Err()).NotTo(HaveOccurred())
Expect(set.Val()).To(Equal("OK"))
type_ := client.Type(ctx, "key")
Expect(type_.Err()).NotTo(HaveOccurred())
Expect(type_.Val()).To(Equal("string"))
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南