Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update a redis value without affecting the remaining TTL?

Tags:

Is it possible to SET redis keys without removing their existing ttl? The only way I know of at the present time is to find out the ttl and do a SETEX but that seems less accurate.

like image 548
paulkon Avatar asked Feb 20 '14 03:02

paulkon


People also ask

Can we set TTL 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.

Is redis TTL in seconds or milliseconds?

Expires and persistence Keys expiring information is stored as absolute Unix timestamps (in milliseconds in case of Redis version 2.6 or greater).

Does redis set overwrite?

Description. Redis SET command is used to set some string value in redis key. If the key already holds a value, it is overwritten, regardless of its type. Any previous time to live associated with the key is discarded on a successful SET operation.

What is the default TTL for redis?

There is no default TTL. By default, keys are set to live forever.


Video Answer


2 Answers

According to Redis documentation, the SET command removes the TTL because the key is overwritten.

However you can use the EVAL command to evaluate a Lua script to do it automatically for you.

The script bellow checks for the TTL value of a key, if the value is positive it calls SETEX with the new value and using the remaining TTL.

local ttl = redis.call('ttl', ARGV[1]) if ttl > 0 then return redis.call('SETEX', ARGV[1], ttl, ARGV[2]) end

Example:

> set key 123

OK

> expire key 120

(integer) 1

... after some seconds

> ttl key

(integer) 97

> eval "local ttl = redis.call('ttl', ARGV[1]) if ttl > 0 then return redis.call('SETEX', ARGV[1], ttl, ARGV[2]) end" 0 key 987

OK

> ttl key

96

> get key

"987"

like image 130
fgasparini Avatar answered Sep 29 '22 19:09

fgasparini


The KEEPTTL option will be added to SET in redis>=6.0

https://redis.io/commands/set

https://github.com/antirez/redis/pull/6679

The SET command supports a set of options that modify its behavior:  EX seconds -- Set the specified expire time, in seconds. PX milliseconds -- Set the specified expire time, in milliseconds. NX -- Only set the key if it does not already exist. XX -- Only set the key if it already exist. (!) KEEPTTL -- Retain the time to live associated with the key. 
like image 25
chistyakov Avatar answered Sep 29 '22 19:09

chistyakov