aioredlock

raw JSON →
0.7.3 verified Fri May 01 auth: no python

Asyncio implementation of Redis distributed locks, providing a reliable mutex mechanism for distributed systems. Current version 0.7.3, with low release cadence. Requires Python >=3.6.

pip install aioredlock
error AttributeError: module 'aioredlock' has no attribute 'Lock'
cause Attempting to import Lock directly from aioredlock, but the correct class is Aioredlock.
fix
Use: from aioredlock import Aioredlock
error TypeError: object str can't be used in 'await' expression
cause Passing a string (e.g., lock name) to unlock() instead of the lock object.
fix
Ensure you store the lock object from lock() and pass it to unlock().
error aioredis.exceptions.ConnectionError: Error 111 connecting to localhost:6379. Connection refused.
cause Redis server is not running or wrong host/port.
fix
Start Redis server or check connection parameters.
gotcha The unlock() method must be called with the lock object returned by lock(), not a string. Passing a string will raise an AttributeError.
fix Always store the lock object from lock() and pass it to unlock().
gotcha The lock manager must be destroyed with await lock_manager.destroy() to close Redis connections. Forgetting to call destroy() will cause connection leaks.
fix Use a try/finally block or context manager to ensure destroy() is called.
deprecated The library relies on aioredis v1.x, which is deprecated. aioredis v2.x changed the API significantly, but aioredlock has not been updated.
fix Pin aioredis<2 or consider migrating to a maintained alternative like redis-py (redis.asyncio).

Basic usage: acquire and release a distributed lock using aioredlock.

import asyncio
from aioredlock import Aioredlock

async def main():
    # Initialize lock manager with Redis connection
    lock_manager = Aioredlock([('localhost', 6379)])
    
    # Acquire a lock
    lock = await lock_manager.lock("my_resource")
    if lock:
        print("Lock acquired")
        # Do critical work
        await asyncio.sleep(1)
        # Release the lock
        await lock_manager.unlock(lock)
    else:
        print("Failed to acquire lock")
    
    # Cleanly close connections
    await lock_manager.destroy()

asyncio.run(main())