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.
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.
Expires and persistence Keys expiring information is stored as absolute Unix timestamps (in milliseconds in case of Redis version 2.6 or greater).
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.
There is no default TTL. By default, keys are set to live forever.
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"
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.
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