denismitr / mutex
PHP互斥库
v0.1
2017-11-21 12:33 UTC
Requires
- php: >=7.0.0
Requires (Dev)
- ext-redis: ^2.2.4|^3
- mockery/mockery: ^0.9.9
- php-mock/php-mock: ^2.0.0
- php-mock/php-mock-phpunit: ^2.0
- phpunit/phpunit: ^6.3
- predis/predis: ~1.0
This package is auto-updated.
Last update: 2024-09-23 08:16:40 UTC
README
作者
安装
composer require denismitr/mutex
使用
使用工厂初始化
- 文件锁
$lock = MutexFactory::fileLock(__FILE__); // or some other file name like /tmp/some-id
- 信号量锁(仅限Linux)
$lock = MutexFactory::semaphoreLock(__FILE__); // or some other file name like /tmp/some-id
- PRedis锁
$this->redis = new Client([ 'host' => 'localhost', 'port' => 6379, 'database' => 0, ]); $this->lock = MutexFactory::pRedisLock($this->redis, "some-key", 20);
目前只支持这些类型的锁
使用锁实例
$lock->acquire(); // Do some critical stuff here $lock->release();
与闭包一起使用
$lock->safe(function() { // Lock will be acuqired and released automatically // Do some critical stuff safely });
先执行检查
$lock->try(function() use ($room, $from, $to) { // e.g return $room->isFree($from, $to); })->then(function() use ($room, $from, $to) { // e.g. // Lock is aquired automatically $room->book($from, $to); })->fail(function() use ($user) { // this callback will fire if the condition in try closure fails // e.g. $user->notify("Room is not available for requested time period."); });
在安全的锁定模式下循环
$lock->loop($timeoutInSeconds, function($loop, $i) ($user, $ads) { // lock is acquired and released automatically when loop is done // e.g. send out only 10 ads to user friends // Laravel collections example $user->friends->each->notify($adds->random()); if ($i >= 10) { $loop->stop(); } });