8

I want to lock a particular key while it is updating. Tried the below example code.

import redis

import time

conn = redis.StrictRedis(host='localhost', port=6379, db=0)

print ("previous Connected Key value is :" + conn.get('connected'))

print ("previous Operational Key value is :" + conn.get('operational'))

have_lock = False
my_lock = redis.Redis().lock("my_key")

try:

    have_lock = my_lock.acquire(blocking=False)
    #have_lock = my_lock.acquire(timeout=5)
    if have_lock:
        print("Got lock. Doing some stuff...")
        time.sleep(15)
        conn.set('connected', 'false')
        conn.set('operational', 'false')
    else:
        print("Did not acquire lock.")

finally:

    if have_lock:
        my_lock.release()
print ("After Connected Key value is :" + conn.get('connected'))

print ('After Operational Key value is :' + conn.get('operational'))

The above code is acquiring the lock, but still I can access the KEY from redis-cli or some other application.

How can I lock the KEY?

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
mrs
  • 207
  • 2
  • 5
  • 13

1 Answers1

15

By design, Redis keys are locked during update, you don't need to lock them. Indeed, Redis uses a single thread to process commands, so each operation is atomic. Other clients are blocked during the processing of a given command, that's why you mustn't perform queries with a long execution time (by example a Lua script you would have written yourself and executed with eval; or a key scan).

Community
  • 1
  • 1
Pascal Le Merrer
  • 5,883
  • 20
  • 35