In redis i am first storing the key vaue. I'll check whether the key is present in the subsequent request using GET command for retrieving value. If a key is not accessed for certain duration like 60min then the key should be deleted. otherwise it should be like that only. So, How can we achieve this requirement. I know TTL feature is present in redis but it'll delete after the specified duration but I wanted the key should be deleted only if it is not accessed for 60min like that.
2 Answers
If you can save your data as key-value pair, i.e. STRING, instead of HASH. You can achieve the goal with SET
command and Lua scripting:
Set Operation
When you need to set a key-value pair, also specify a TTL to ensure if there's no access within 60s, the key will be deleted automatically:
SET key value EX 60
Get Operation
When you try to get the value, if the key exists, also reset its TTL to 60s with Lua script:
-- get.lua
local key = KEYS[1]
local val = redis.call("get", key)
if (val) then
redis.call("expire", key, 60)
end
return val
NOTE: If you don't want to specify a TTL with the SET command every time, or your Redis version doesn't support EX
option, you can also wrap the SET
and EXPIRE
commands into a Lua script.

- 21,012
- 4
- 35
- 48
TTL in redis cannot be set per KEY in the hset, only per whole set The reason is that the implementation would be complicated and the creators of redis wanted to keep it as simple as possible.
Here are some workarounds:
- Instead of hset use a top level set/get with TTL/EXPIRE commands
- in the value store the expiration time, when you get the value also update the expiration time, issue a delete command from client that gets key/value and discovers that is was supposed to be expired already

- 39,963
- 4
- 57
- 97
-
instead of hset I can use set/get aslo for storing not a problem. But is there any other approach instead of updating expiration time each time – rahul Jul 14 '20 at 13:16
-
I don't think its possible. I've google for similar questions now and found this thread: https://stackoverflow.com/questions/16545321/how-to-expire-the-hset-child-key-in-redis Looks related – Mark Bramnik Jul 14 '20 at 13:19