1. 问题描述
今天使用 redis 遇到个奇怪的问题,key 设置过期时间后,到期后并没有删除。
语句过程大概如下:
127.0.0.1:6379> SET hello 0
OK
127.0.0.1:6379> GET hello
"0"
127.0.0.1:6379> EXPIRE hello 20
(integer) 1
127.0.0.1:6379> TTL hello
(integer) 16
127.0.0.1:6379> INCR hello
(integer) 1
127.0.0.1:6379> TTL hello
(integer) -1
用了很久 redis,也是第一次遇到这个问题,而且这个现象不是必现的。
2. 排查原因
起初怀疑可能原因:
- 版本问题
- 命令用法问题
将版本升级到最新版,之后还是有几率遇到这个问题。
难道是INCR
用法有问题?查看官网命令文档,也说INCR
并不会改变key
的生存时间。
For instance, incrementing the value of a key with INCR, pushing a new value into a list with LPUSH, or altering the field value of a hash with HSET are all operations that will leave the timeout untouched.
有些不解,只好 Google 了,发现有人和我遇到类似的事情。
https://stackoverflow.com/questions/11849153/my-redis-keys-do-not-expire
https://github.com/antirez/redis/issues/4187
遗憾的是,他们当时好像也没有找出原因以及解决办法,只好自己摸索了。
经过不断的尝试,最后大致是这样解决的:
result = redis.get(hello)
if result == NULL
redis.setex(hello, 20, 0)
else
redis.incr(hello)
问题是解决了,可是依旧很困惑,不知道是什么原理。
如果你恰巧知道,希望能留言解我疑惑,谢谢。
参考
https://redis.io/commands/expire
https://redis.io/commands/incr