Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis locking for a KEY

Tags:

python

redis

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?

like image 286
mrs Avatar asked Sep 28 '16 05:09

mrs


1 Answers

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).

like image 166
Pascal Le Merrer Avatar answered Oct 05 '22 19:10

Pascal Le Merrer