yiisoft / mutex-pdo-mysql
Yii Mutex 库 - MySQL PDO 驱动
1.1.0
2021-10-19 07:18 UTC
Requires
- php: ^7.4|^8.0
- ext-pdo: *
- yiisoft/mutex: ^1.1
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:19:50 UTC
README
Yii Mutex 库 - MySQL PDO 驱动
本库为 yiisoft/mutex 提供MySQL互斥锁实现。
要求
- PHP 7.4 或更高版本。
PDO
PHP 扩展。
安装
可以使用 Composer 安装此包。
composer require yiisoft/mutex-pdo-mysql
通用用法
此包提供了两个类,实现了 yiisoft/mutex 包中的 MutexInterface
和 MutexFactoryInterface
。
/** * @var \PDO $connection Configured for MySQL. */ $mutex = new \Yiisoft\Mutex\Mysql\MysqlMutex('mutex-name', $connection); $mutexFactory = new \Yiisoft\Mutex\Mysql\MysqlMutexFactory($connection);
你可以有多种方式使用此包。你可以在同步模式下执行回调,即同一时间只有一个回调实例被执行。
$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();
MysqlMutex
支持等待一定时间获取锁的功能。使用 withRetryDelay()
方法,你可以覆盖每次尝试之间的毫秒数,直到指定的超时时间超时
$mutex = $mutex->withRetryDelay(100);
默认情况下,它是 50 毫秒 - 这意味着我们可能每秒尝试获取锁高达 20 次。
文档
如果你需要帮助或有任何问题,Yii 论坛 是一个不错的选择。你也可以查看其他 Yii 社区资源。
许可证
Yii Mutex 库 - MySQL PDO 驱动是自由软件。它按照 BSD 许可证的条款发布。有关更多信息,请参阅 LICENSE
。
由 Yii 软件 维护。