Redis distributed lock implementation for Python based on Pub/Sub messaging
Project description
Redis Lock with PubSub
Redis distributed lock implementation for Python based on Pub/Sub messaging.
1. Features
- Ensure atomicity by using SETNX operation
- Pub/Sub messaging system between the client waiting to get the lock and holding the lock
- Force timeout to avoid infinite loops when trying to acquire lock
- Async is supported
2. Installation
$> pip install redis-lock-py
Dependencies
- Python >= 3.7
- redis-py >= 4.2.0
3. Usage
3.1 Basic Example
import redis
from redis_lock import RedisLock
client = redis.Redis(host="127.0.0.1", port=6379)
name = "foo"
lock = RedisLock(client, name)
if not lock.acquire():
raise Exception("Fail to acquire lock")
print("Acquired lock successfully!")
lock.release()
redis-py library is required for redis connection objects.
The RedisLock.release
method must be invoked to release the lock after acquiring a lock successfully by calling RedisLock.acquire
method with returned True
.
3.2 Using Context Managers
import redis
from redis_lock import RedisLock
client = redis.Redis(host="127.0.0.1", port=6379)
with RedisLock(client, "foo", blocking_timeout=10):
print("Acquired lock successfully!")
If the part that releases the lock is missing after acquire a lock,
all the clients that access the same name
may not be able to acquire the lock.
To prevent this unexpected malfunction from happening, programmed to unlock the lock by itself at the end of the with
context.
Both examples in 3.1 and 3.2 work the same way.
3.3 Using Spin Lock
import redis
from redis_lock import RedisSpinLock
client = redis.Redis(host="127.0.0.1", port=6379)
lock = RedisSpinLock(client, "foo")
if not lock.acquire(blocking=True, sleep_time=0.1):
raise Exception("Fail to acquire lock")
print("Acquired lock successfully!")
lock.release()
Spin lock is also available, but not recommended unless there is a compelling reason to use them because of inefficiency compare to the Pub/Sub messaging system.
System Flow
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for redis_lock_py-0.2.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9fc6475b44336d9e46c519cdfe591e4d41a360f62ae6b2f6e290baabd034ba2b |
|
MD5 | 5d88c3bbb9f02c23f500b2179d15f76a |
|
BLAKE2b-256 | bb16a647723d39cec2b2d13622a88bce21446b5ee25fe05f70d288e9e81e4a8b |