Home > Software design >  How to add a running to Redis?
How to add a running to Redis?

Time:11-03

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?

CodePudding user response:

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

CodePudding user response:

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
  • Related