I'm interacting with Redis through PHPRedis (actually a higher level wrapper built around PHPRedis). I want to update a key and reset it in the database, but the TTL should be reset to the original value at the current point in the program my Class doesn't know what the original TTL.
So say the original TTL was 12 hours. I want to do something like this:
redis->get($key)
$original_ttl = // figure it out
$new_value = something
redis->set($key, $new_value, $original_ttl)
Then we end up with the original key referencing a new value and another 12 hours ttl. Is this possible?
Just use two commands: a SET to update the value and then an EXPIRE to update the TTL.
Update: To retrieve the original TTL you have to store it in a separate key. As far as I know, you can get the current TTL, but not its initial value.
So it would look like this in pseudo code (REDIS commands are in capitals):
SET myKey value
EXPIRE myKey 3600
SET myKey:ttl 3600
to fix the TTL to 3600s
and then
SET myKey newValue
ttlvalue = GET mykey:ttl
EXPIRE myKey ttlvalue
Update 2 :
My response may be improved using Agis' suggestion to use SETEX, which sets a value for a given key and its expiration date in one operation. So it would become:
SETEX myKey 3600 value
SET myKey:ttl 3600
to fix the TTL to 3600s
and then
ttlvalue = GET mykey:ttl
SETEX myKey ttlvalue newValue
to update the value and reset its TTL
You could define the initial TTL value in a constant somewhere in your code and use it everytime you set a key.
Then use SETEX
to both set the value and the expiration time of the key:
define('TTL', 120); // 2 minutes
redis->setex($key, TTL, $new_value);
The equivalent command in Redis would be like:
> SETEX mykey 120 "myvalue"
If you want to set the time in milliseconds instead of seconds, then use PSETEX
.
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