yiisoft/mutex-file

Yii互斥库 - 文件驱动

1.1.1 2022-09-04 19:25 UTC

This package is auto-updated.

Last update: 2024-09-16 12:35:15 UTC


README

Yii互斥库 - 文件驱动


Latest Stable Version Total Downloads Build status Scrutinizer Code Quality Code Coverage Mutation testing badge static analysis type-coverage

此库为 yiisoft/mutex 提供文件互斥实现。

要求

  • PHP 7.4 或更高版本。

安装

可以使用 Composer 安装此包

composer require yiisoft/mutex-file

通用用法

该包提供了两个类,实现了来自 yiisoft/mutex 包的 MutexInterfaceMutexFactoryInterface 接口。

$mutex = new \Yiisoft\Mutex\File\FileMutex(
    'mutex-name',
    '/path/to/directory/for/storing/mutex/files',
    0775, // Optional. The permission to be set for newly created mutex directory. Default is `0775`.
    0777, // Optional. The permission to be set for newly created mutex files. Default is `null`.
);

$mutexFactory = new \Yiisoft\Mutex\File\FileMutexFactory(
    '/path/to/directory/for/storing/mutex/files',
    0775, // Optional. The permission to be set for newly created mutex directory. Default is `0775`.
    0777, // Optional. The permission to be set for newly created mutex files. Default is `null`.
);

您可以使用多种方式使用此包。您可以在同步模式下执行回调,即同一时间只执行单个回调实例

$synchronizer = new \Yiisoft\Mutex\Synchronizer($mutexFactory);

$newCount = $synchronizer->execute('critical', function () {
    return $counter->increase();
}, 10);

另一种方法是手动打开和关闭互斥锁

$simpleMutex = new \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();

FileMutex 支持等待一定时间锁定的功能。使用 withRetryDelay() 方法,您可以覆盖每次尝试之间的毫秒数,直到指定的超时时间超时

$mutex = $mutex->withRetryDelay(100);

默认情况下,它是 50 毫秒 - 这意味着我们可能每秒尝试获取锁多达 20 次。

文档

如果您需要帮助或有问题,Yii 论坛 是一个好地方。您还可以查看其他 Yii 社区资源

许可证

Yii互斥库 - 文件驱动是免费软件。它根据BSD许可证的条款发布。有关更多信息,请参阅 LICENSE

Yii 软件 维护。

支持项目

Open Collective

关注更新

Official website Twitter Telegram Facebook Slack