Ahasanul Haque
Ahasanul Haque

Reputation: 11134

How to reset TTL when a redis key is accessed?

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?

Upvotes: 18

Views: 10811

Answers (1)

ntki
ntki

Reputation: 2304

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

Upvotes: 20

Related Questions