Optimistic locking with redis using GET and INCR

I want to “block” the code block optimistically. The psuedo code is as follows:

revision = GET('lock_key') # default as 0
{
<<block of code>>
}
new_revision = INCR('lock_key')
if new_revision != revision + 1:
    raise Exception # now retry or whatever

This looks good to me, since INCR and GET are atomic. Do you see any problems with this approach?

+4
source share
1 answer

. -, , . , , , . , , INCRing key_lock.

Redis 'MULTI, EXEC WATCH. Redis ' psuedo:

WATCH('lock_key')
revision = GET('lock_key') # default as 0
{
    <<block of code>>
}

MULTI()
new_revision = INCR('lock_key')
if EXEC() is None:
  raise Exception # now retry or whatever
+4

Source: https://habr.com/ru/post/1540509/


All Articles