How do I set expiry for hashmaps in Redis like I do for regular values using SETX. I want to provide TTL for a session for which I am storing a hasmap. Can I create a Hashmap using SETEX itself ?
No, you can't create hash with SETEX
(which is a strings methods). You can call EXPIRE
on hash key, but that will expire the whole hash. There's no support at the moment for expiration of individual hash key/value pairs.
If you wanted to set expiration on the whole hash while setting its individual elements, you can achieve that in several ways.
Use pipelining. Pipelining is a special mode of operation where redis client issues several commands in quick succession, not waiting for a reply to send next one. Here's an example in ruby:
redis.pipelined do
redis.hset "foo", "bar", 1
redis.expire "foo", 300
end
Use transactions. Without watched keys this is similar to pipelining (for a transaction can't abort). The commands are guaranteed to run together and atomically (several pipelines can run interleaved, transactions are serialized)
redis.multi do
redis.hset "foo", "bar", 1
redis.expire "foo", 300
end
Use lua scripting to implement your custom HSETEX command. It will be executed atomically and you just have to send one command (instead of 2(pipelining) or 4 (transaction)).
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