yiisoft / mutex-db-redis
1.1.0
2021-10-19 07:13 UTC
Requires
- php: ^7.4|^8.0
- predis/predis: ^1.1
- yiisoft/mutex: ^1.1
- yiisoft/security: ^1.0
Requires (Dev)
- phpunit/phpunit: ^9.5
- roave/infection-static-analysis-plugin: ^1.9
- spatie/phpunit-watcher: ^1.23
- vimeo/psalm: ^4.9
This package is auto-updated.
Last update: 2024-05-20 10:28:46 UTC
README
Yii Mutex 库 - Redis 驱动
此库为 yiisoft/mutex 提供Redis互斥锁实现。
要求
- PHP 7.4 或更高版本。
安装
可以使用 Composer 安装此包
composer require yiisoft/mutex-redis
通用用法
该包提供了两个类,实现了 yiisoft/mutex 包中的 MutexInterface
和 MutexFactoryInterface
。
/** * @var \Predis\ClientInterface $client Predis client instance to use. */ $mutex = new \Yiisoft\Mutex\Redis\RedisMutex( 'mutex-name', $client, 60, // Optional. Number of seconds in which the lock will be auto released. Default is `30`. ); $mutexFactory = new \Yiisoft\Mutex\Redis\RedisMutexFactory( $client, 60, // Optional. Number of seconds in which the lock will be auto released. Default is `30`. );
有关客户端实例和连接配置的更多信息,请参阅 predis/predis 包的文档。
您可以使用多种方式使用此包。您可以在同步模式下执行回调,即同一时间只执行一个回调实例
$synchronizer = new \Yiisoft\Mutex\Synchronizer($mutexFactory); $newCount = $synchronizer->execute('critical', function () { return $counter->increase(); }, 10);
另一种方式是手动打开和关闭互斥锁
$simpleMutex = \Yiisoft\Mutex\SimpleMutex($mutexFactory); if (!$simpleMutex->acquire('critical', 10)) { throw new \Yiisoft\Mutex\Exception\MutexLockedException('Unable to acquire the "critical" mutex.'); } $newCount = $counter->increase(); $simpleMutex->release('critical');
这可以在较低级别完成
$mutex = $mutexFactory->createAndAcquire('critical', 10); $newCount = $counter->increase(); $mutex->release();
如果您需要更多控制,您可以手动获取互斥锁
$mutex = $mutexFactory->create('critical'); if (!$mutex->acquire(10)) { throw new \Yiisoft\Mutex\Exception\MutexLockedException('Unable to acquire the "critical" mutex.'); } $newCount = $counter->increase(); $mutex->release();
RedisMutex
支持等待一段时间获取锁的功能。使用 withRetryDelay()
方法,您可以覆盖每次尝试之间的毫秒数,直到指定的超时时间超时
$mutex = $mutex->withRetryDelay(100);
默认情况下,它是50毫秒 - 这意味着我们可能每秒尝试获取锁多达20次。
文档
如果您需要帮助或有问题,Yii 论坛 是一个好地方。您还可以查看其他 Yii 社区资源。
许可证
Yii Mutex Library - Redis 驱动是免费软件。它根据BSD许可证发布。有关更多信息,请参阅 LICENSE
。
由 Yii Software 维护。