Skip to content
This repository has been archived by the owner on May 5, 2021. It is now read-only.

Add context manager support #25

Open
dmitryzv opened this issue Jul 28, 2017 · 4 comments
Open

Add context manager support #25

dmitryzv opened this issue Jul 28, 2017 · 4 comments

Comments

@dmitryzv
Copy link

It would be nice to use it as context manager. Like the following:

with Redlock([{"host": "localhost", "port": 6379, "db": 0}, ]) as dlm:
    do_sync_stuff()
@Darkheir
Copy link

Darkheir commented Dec 5, 2018

The thing is the lock is not acquired when instantiating Redlock but when calling dlm.lock("my_resource_name",1000)

The code could be changed to

with  dlm.lock("my_resource_name",1000) as lock:
    pass

but we would still need to handle the case where the lock failed. Then an exception needs to be raised and this is something that is not done in the original code.

@ParetoLife
Copy link

I mean, a threading.Lock is also not acquired when instantiated, but still works exactly like dmitryzv proposes as a context manager: threading.Lock docs.
If the lock failed you could just make it try again (blocking=True) or raise an exception.

To me mirroring the standard threading.Lock feels very intuitive.

@TsingJyujing
Copy link

You may try this piece of code:
https://github.com/TsingJyujing/nemivir/blob/master/nemivir/util/distributed_lock.py#L9-L27

class RedisDistributedLock:
    def __init__(self, redis_lock: Redlock, lock_key: str, ttl: int = 30):
        """
        A context based redis distributed lock
        :param redis_lock: Redlock object
        :param lock_key: the resource key to lock
        :param ttl: timout after ttl seconds
        """
        self._rlk = redis_lock
        self._key = lock_key
        self._ttl = ttl
        self._lock = None

    def __enter__(self):
        self._lock = self._rlk.lock(self._key, self._ttl)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._rlk.unlock(self._lock)

And here's an example:

with RedisDistributedLock(Redlock(<connection info>),<key>,<ttl>) as rdl:
    # do something

@brainix
Copy link

brainix commented Mar 18, 2021

redlock-py looks like a nice project, but the last commit was on March 8, 2016. It doesn’t look like redlock-py is maintained.

Consider using Pottery’s implementation of Redlock instead (I develop/maintain Pottery). Pottery’s Redlock has a couple of nice features over redlock-py:

  1. Pottery’s Redlock is closer to Python’s threading.Lock, so you can use it as a context manager
  2. Pottery’s Redlock executes commands against the multiple Redis instances in parallel (redlock-py is serial), so Pottery is slightly more performant

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants