yiisoft / mutex-redis
Yii Mutex 库 - 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-09-20 11:13:15 UTC
README
Yii Mutex 库 - Redis 驱动程序
此库为 yiisoft/mutex 提供了一个 Redis mutex 实现。
要求
- 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 Driver 是免费软件。它根据 BSD 许可证的条款发布。有关更多信息,请参阅 LICENSE
。
由 Yii Software 维护。