1. 程式人生 > >redis expire key 過期不刪除

redis expire key 過期不刪除

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.

遺憾的是,他們當時好像也沒有找出原因以及解決辦法,只好自己摸索了。
經過不斷的嘗試,最後大致是這樣解決的:

result = redis.get(hello)
if result == NULL
    redis.setex(hello, 20, 0)
else
    redis.incr(hello)

問題是解決了,可是依舊很困惑,不知道是什麼原理。
如果你恰巧知道,希望能留言解我疑惑,謝謝。

參考