Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set expiry for Hashmap values in Redis?

Tags:

redis

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 ?

like image 616
Amogh Talpallikar Avatar asked Nov 29 '13 14:11

Amogh Talpallikar


1 Answers

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.

Update:

If you wanted to set expiration on the whole hash while setting its individual elements, you can achieve that in several ways.

  1. 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
    
  2. 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
    
  3. 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)).

like image 61
Sergio Tulentsev Avatar answered Sep 23 '22 03:09

Sergio Tulentsev