I have some keys with TTL in redis. So, normally the key will be evicted when the TTL passed.
But what I want to do is, in every access (retrieval) to the key, I will want to reset the TTL to the original value I set earlier.
For example: I have set 2 hours for a key. After 1 hour later, the key is accessed. I want to set the TTL to 2 hours again at that time. So, the key will only be evicted if it's not accessed in its TTL lifetime.
How to do this efficiently?
No, Redis doesn't have a notion of a global/default TTL and yes, you do have to set it for each key independently.
When a key has an expire set, Redis will make sure to remove the key when the specified amount of time elapsed. The key time to live can be updated or entirely removed using the EXPIRE and PERSIST command (or other strictly related commands).
Redis TTL command is used to get the remaining time of key expiry in seconds. Returns the remaining time to live of a key that has a timeout. This introspection capability allows a Redis client to check how many seconds a given key will continue to be part of the dataset.
To create a Redis with an expiration time, use the SET command and the EX option to set the expiration time. The EX option takes a number in seconds and sets the number of seconds the key is valid until expiration. You can also use PX to specify the expiration time in Milliseconds.
You can only do this by issuing another EXPIRE
command with the accessing command. Even the official documentation does not mention any other option.
You might want to put these commands on a pipeline to have a better response time.
For example:
connection = redis.StrictRedis()
with connection.pipeline() as pipe:
pipe.get("key")
pipe.expire("key", 7200)
pipe.execute()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With