Locks¶
- class Lock(client: Redis | RedisCluster, name: StringT, timeout: float | None = None, sleep: float = 0.1, blocking: bool = True, blocking_timeout: float | None = None)[source]¶
A shared, distributed Lock inspired by the Distributed locks documentation and the Redlock Algorithm
The lock can be used with both
RedisandRedisClustereither explicitly or as an async context manager:import asyncio import coredis from coredis.exceptions import LockError from coredis.patterns.lock import Lock client = coredis.Redis() async with client: async with Lock(client, "mylock", timeout=1.0): # do stuff await asyncio.sleep(0.5) # lock is implictly released when the context manager exits try: async with Lock(client, "mylock", timeout=1.0): # do stuff that takes too long await asyncio.sleep(1) # lock will raise upon exiting the context manager except LockError as err: # roll back stuff print(f"Expected error: {err}")
- Parameters:
timeout¶ – indicates a maximum life for the lock. By default, it will remain locked until
release()is called.timeoutcan be specified as a float or integer, both representing the number of seconds to wait.sleep¶ – indicates the amount of time to sleep per loop iteration when the lock is in blocking mode and another client is currently holding the lock.
blocking¶ – indicates whether calling
acquire()should block until the lock has been acquired or to fail immediately, causingacquire()to returnFalseand the lock not being acquired. Defaults toTrue.blocking_timeout¶ – indicates the maximum amount of time in seconds to spend trying to acquire the lock. A value of
Noneindicates continue trying forever.blocking_timeoutcan be specified as afloatorint, both representing the number of seconds to wait.
- async acquire() bool[source]¶
Use SET with the
NXoption to acquire a lock. If the lock is being used with a cluster client theensure_replication()context manager will be used to ensure that the command was replicated to atleast half the replicas of the shard where the lock would be acquired.- Raises: