skip to Main Content

From several servers I would like to add keys like doc:1 and then doc:2 etc.

Now in order that the different servers do not try to add to, say, doc:2 at the same time, I thought there is some mechanism like "add to doc:{index}" and the index gets automatically bumped.

Is there some way to make that work?

2

Answers


  1. You could use a distributed lock and have the winner write

    for each server, attempt to acquire lock until success
    on acquire lock
      read numeric value
      increment
      write
      release lock
    

    docs

    Login or Signup to reply.
  2. You could use a key which you increment on every addition: the INCR command does just that, atomically, and returns the incremented value which you can use to generate the new key name.

    > INCR counter
    42
    
    > SET doc:42 foobar
    OK
    

    Update: in the event you want the whole set of operations (incrementing the counter and setting the value) to be atomic, you can execute a Lua script instead:

    > EVAL "local value = redis.call('INCR', 'counter'); redis.call('SET', 'doc:'..value, ARGV[1])" 0 foobar
    (nil)
    

    Explanation:

    local value = redis.call('INCR', 'counter');
    

    Execute INCR counter and store the result in the value variable.

    redis.call('SET', 'doc:'..value, ARGV[1]);
    

    Execute SET against the key named after the concatenation of doc: and the value variable using the data passed through the first EVAL argument – in our case foobar.

    Finally, should you need to return the incremented counter value to the caller just append a final return value; block to the script.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search