How Python uses redis to build distributed locks

Time:2020-10-31

This article mainly introduces how Python uses redis to build distributed locks. This article introduces in detail the example code, which has a certain reference learning value for everyone’s study or work. Friends in need can refer to it

In the actual application scenario, we may have multiple workers, which may be in one machine or distributed in different machines, but only one worker can hold a lock at the same time. At this time, we need to use distributed locks.

Here we recommend redlock py, the python implementation library

Under normal circumstances, after the worker obtains the lock, it will process its own task and release the lock automatically after completion. It is easy to think of our context manager. Here we simply use decorator to implement with… As… Syntax.

Install redlock PY

$ pip install redlock-py

Try context management with Python’s own contextmanager decorator

from contextlib import contextmanager
from redlock import Redlock

@contextmanager
def worker_lock_manager(key, ttl, **kwargs):
  """
  Distributed lock
  :param key: Distributed lockID
  :param ttl: Distributed lock生存时间
  : param kwargs: optional parameter dictionary
  :return: None
  """
  redis_servers = [{
    'host': '127.0.0.1',
    'port': 6379,
    'db': 0,
    'password': 'pwd'
  }]

  rlk= Redlock(redis_servers)

  #Get lock
  lock = rlk.lock(key, ttl)
 
  yield lock

  #Release the lock
  rlk.unlock(lock)

How to use it


with worker_lock_manager('unique_key', 1000) as w_lock:
    if w_lock is False:
        return
    do_something()

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.