Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redis locking: redispy vs python-redis-lock

Except that python-redis-lock module provides contextmanager for the lock object - what are the differences when compared to the lock object you get from redispy module? what is so special about python-redis-lock?

rc = Redis.from_url(settings.BROKER_URL)
lock_str = "bld-%s-lock" % bld_id

Using redispy:

lock = rc.lock(lock_str)

Using python-redis-lock:

lock = redis_lock.Lock(rc, lock_str)
like image 339
Murali Mopuru Avatar asked Sep 12 '18 12:09

Murali Mopuru


People also ask

What is Redis locking?

The simplest way to use Redis to lock a resource is to create a key in an instance. The key is usually created with a limited time to live, using the Redis expires feature, so that eventually it will get released (property 2 in our list). When the client needs to release the resource, it deletes the key.

Does Redis work with Python?

redis-py (which you import as just redis ) is one of many Python clients for Redis, but it has the distinction of being billed as “currently the way to go for Python” by the Redis developers themselves.

What is Redis StrictRedis?

source code object --+ | StrictRedis. Implementation of the Redis protocol. This abstract class provides a Python interface to all Redis commands and an implementation of the Redis protocol. Connection and Pipeline derive from this, implementing how the commands are sent and received to the Redis server.

What is Redis Redlock?

In a system, sometimes you must lock a resource. This might be to make critical modifications that cannot be resolved in any concurrent way. The goals for locks are: One worker (and only one) worked to be able to acquire rights to a resource.


1 Answers

I think the context manager is not the major difference here, because if you see code of redis-py Lock they have the __enter__ and __exit__ added in there.

Both the Lock's seem to use SETNX for acquiring the lock:

  • python-redis-lock: Github
  • redis-py Lock: Github

The major difference I saw in there was the way blocking the threads work.

  • In case of python-redis-lock they have been using BLPOP mechanism to block the thread, which to me seems like using redis's own version of blocking mechanism. Github code

Something like:

timed_out = not self._client.blpop(self._signal, blpop_timeout) and timeout

  • In case of redis-py they seem use time module and its sleep method to block the thread to check whether the blocking has timedout.

Something like:

import time as mod_time

...
stop_trying_at = mod_time.time() + blocking_timeout
...
mod_time.sleep(sleep)
like image 142
Nagaraj Tantri Avatar answered Oct 02 '22 14:10

Nagaraj Tantri