Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset TTL when a redis key is accessed?

Tags:

python

redis

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?

like image 723
Ahsanul Haque Avatar asked Sep 08 '19 14:09

Ahsanul Haque


People also ask

Can we set TTL in Redis?

No, Redis doesn't have a notion of a global/default TTL and yes, you do have to set it for each key independently.

What happens when TTL expires Redis?

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).

How will you find the time to live for a key A in Redis?

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.

How do I change the expiration date on Redis cache?

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.


Video Answer


1 Answers

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()
like image 195
ntki Avatar answered Nov 09 '22 23:11

ntki