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
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:
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:
Get Operation
When you try to get the value, if the key exists, also reset its TTL to 60s with Lua script:
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 theSET
andEXPIRE
commands into a Lua script.