texthtml / php-lock-redis
redis lock
Installs: 64 577
Dependents: 1
Suggesters: 0
Security: 0
Stars: 6
Watchers: 3
Forks: 6
Open Issues: 1
Requires
- ext-pcntl: *
- predis/predis: ~1.0
- psr/log: ~1.0
- texthtml/php-lock: ~2.1
Requires (Dev)
- phpunit/phpunit: ~4.0
This package is auto-updated.
Last update: 2024-10-28 00:18:32 UTC
README
php-lock-redis is an extension for php-lock that makes locking on resources easy on distributed system using Redis. It can be used instead of file base locking to lock operations on a distributed system.
Installation
With Composer :
composer require texthtml/php-lock-redis
Usage
You can create an object that represent a lock on a resource. You can then try to acquire that lock by calling $lock->acquire()
. If the lock fail it will throw an Exception
(useful for CLI tools built with Symfony Console Components documentation). If the lock is acquired the program can continue.
Locking a ressource
use TH\RedisLock\RedisSimpleLockFactory; $redisClient = new \Predis\Client; $factory = new RedisSimpleLockFactory($redisClient); $lock = $factory->create('lock identifier'); $lock->acquire(); // other processes that try to acquire a lock on 'lock identifier' will fail // do some stuff $lock->release(); // other processes can now acquire a lock on 'lock identifier'
Auto release
$lock->release()
is called automatically when the lock is destroyed so you don't need to manually release it at the end of a script or if it goes out of scope.
use TH\RedisLock\RedisSimpleLockFactory; function batch() { $redisClient = new \Predis\Client; $factory = new RedisSimpleLockFactory($redisClient); $lock = $factory->create('lock identifier'); $lock->acquire(); // lot of stuff } batch(); // the lock will be released here even if $lock->release() is not called in batch()
Limitations
Validity time
If a client crashes before releasing the lock (or forget to release it), no other clients would be able to acquire the lock again. To avoid Deadlock, RedisSimpleLock
locks have a validity time at witch the lock key will expire. But be careful, if the operation is too long, another client might acquire the lock too.
Mutual exclusion
Because RedisSimpleLock
does not implements the RedLock algorithm, it have a limitation : with a master slave replication, a race condition can occurs when the master crashes before the lock key is transmitted to the slave. In this case a second client could acquire the same lock.