I used to do client.setex(key, 900, value)
for storing single key-value.
But, I want to store an object with expiration time.
I come up with function hmset
, but I don't know how to make expiration time.
I want to use it to store the context and the text of current chat in conversation.
Please help
As noted in the accepted answer, expiration in Redis is only performed at key-level - nested elements cannot be expired. To "expire" items, call ZREMRANGEBYSCORE from -inf and the current epoch minus 24 hours.
After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology. The timeout will only be cleared by commands that delete or overwrite the contents of the key, including DEL , SET , GETSET and all the *STORE commands.
Redis HMSET command is used to set the specified fields to their respective values in the hash stored at the key. This command overwrites any existing fields in the hash. If the key does not exist, a new key holding a hash is created.
To expire a Hash (or any other Redis key for that matter), call the EXPIRE
command. In your case:
client.hmset(key, ...
client.expire(key, 9000)
Since, hmset
is deprecated (see this), you can use hset
with expire
using pipeline
.
pipe = client.pipeline()
pipe.hset(key, mapping=your_object).expire(duration_in_sec).execute()
# for example:
pipe.hset(key, mapping={'a': 1, 'b': 2}).expire(900).execute()
Note: Pipeline does not ensure atomicity.
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