Search code examples
redisspring-dataspring-data-redis

Is there any ways to evict keys from Redis just after accessing it?


As per this answer [https://stackoverflow.com/a/17099452/8804776][1]

"You might not know it, but Redis is actually single-threaded, which is how every command is guaranteed to be atomic. While one command is executing, no other command will run."

Redis is single threaded. My requirement is to store a key in Redis and as soon as a thread access it it should evict.

eg: HSET bucket-1 name justin

Thread A and B accessing the same key HGET bucket-1 name
Only one thread should get the data at any given point.

Is there any particular settings that i can do to achieve this?


Solution

  • The term "eviction" refers to keys that have an expiry set (TTL). While there is no dedicated command to achieve what you want, you can use a transaction such as:

    WATCH bucket-1
    HGET bucket-1 name
    (pseudo: if not nil)
    MULTI
    HDEL bucket-1 name
    EXEC
    

    If the EXEC fails it means you're in thread B (assuming that A got there first).

    Alternatively, the above can be compacted into an idiomatic Lua script - as suggested by @The_Dude - such as (newlines added for readability):

    EVAL "local v=redis.call('HGET', KEYS[1], ARGV[1])
          redis.call('HDEL', KEYS[1], ARGS[1])
          return v" 
          1 bucket-1 name
    

    A nil reply means you're B.