He Shuang
He Shuang

Reputation: 53

Redis: How to update a key but do not change it's expiration time?

Using Redis as cache service to cache some non-important data, and there is a case that need to update the value without reset or override the expire time, is there any good way to resolve this problem? I've searched and found follows 2 solutions

  1. Using setrange command, since the value is a little more complex, so it is not good in this situation.
  2. Get the ttl time then set it as the expiration time when update the value. it's seems a little more redundant.

Any good idea to resolve this problem?

Upvotes: 5

Views: 7309

Answers (2)

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181280

You don't need to do any of those two things. You just need to use the KEEPTTL flag when you set your value.

Like this:

> set my_key this_is_my_value EX 60

This will set a value for a key with 60 seconds expiration.

Then, when you change the value and don't want to change the expiration of your key, just do:

> set my_key this_is_my_new_value KEEPTTL

More information on REDIS docs.

Upvotes: 8

Ayon
Ayon

Reputation: 65

Another idea to so resolve this could be using INCRBY.

For this you have to do some steps.

  1. Get the existing value. For example, 10.
  2. Determine the update value.For example, 17 .
  3. INCRBY the value of their difference 17-10. That means, 7

This won't change the ttl

Upvotes: 1

Related Questions