0

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?

Justin Mathew
  • 950
  • 8
  • 34

2 Answers2

0

There isn't a command to do that with hashes. You could use a Lua script to handle this.

You could also use GETSET instead, where you can reset a key to a value that denotes it has been used by another consumer.

TheDude
  • 3,796
  • 2
  • 28
  • 51
0

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.

Itamar Haber
  • 47,336
  • 7
  • 91
  • 117