pudongping/hyperf-wise-locksmith
Composer 安装命令:
composer require pudongping/hyperf-wise-locksmith
包简介
A mutex library provider for the Hyperf framework, designed to enable serialized execution of PHP code in high-concurrency scenarios.
README 文档
README
Requirements | Installation | Branches or tags | Quickstart | Note | Documentation | Contributing | License
hyperf-wise-locksmith
English | 中文
🔒 A mutex library provider for the Hyperf framework, designed to enable serialized execution of PHP code in high-concurrency scenarios. This library is based on pudongping/wise-locksmith.
Requirements
- PHP >= 8.1
- hyperf ~3.1.0
Installation
composer require pudongping/hyperf-wise-locksmith:^3.0 -vvv
Branches or tags
Branch
- 2.2: For hyperf 2.2
- 3.0: For hyperf ~3.0
- 3.1: For hyperf ~3.1
Tag
- 1.0.x: For hyperf 2.2
- 2.0.x: For hyperf 3.0
- 3.0.x: For hyperf 3.1
Quickstart
Below, an example of deducting user balances in a high-concurrency scenario will be provided to demonstrate the functionality and usage of this library.
Create the app\Controller\BalanceController.php file and write the following code:
<?php declare(strict_types=1); namespace App\Controller; use Hyperf\HttpServer\Annotation\AutoController; use App\Services\AccountBalanceService; use Hyperf\Coroutine\Parallel; use function \Hyperf\Support\make; #[AutoController] class BalanceController extends AbstractController { // curl '127.0.0.1:9511/balance/consumer?type=noMutex' public function consumer() { $type = $this->request->input('type', 'noMutex'); $amount = (float)$this->request->input('amount', 1); $parallel = new Parallel(); $balance = make(AccountBalanceService::class); // 模拟 20 个并发 for ($i = 1; $i <= 20; $i++) { $parallel->add(function () use ($balance, $i, $type, $amount) { return $balance->runLock($i, $type, $amount); }, $i); } $result = $parallel->wait(); return $this->response->json($result); } }
Next, create the app\Services\AccountBalanceService.php file and write the following code:
<?php declare(strict_types=1); namespace App\Services; use Hyperf\Contract\StdoutLoggerInterface; use Pudongping\HyperfWiseLocksmith\Locker; use Pudongping\WiseLocksmith\Exception\WiseLocksmithException; use Pudongping\WiseLocksmith\Support\Swoole\SwooleEngine; use Throwable; class AccountBalanceService { /** * 用户账户初始余额 * * @var float|int */ private float|int $balance = 10; public function __construct( private StdoutLoggerInterface $logger, private Locker $locker ) { $this->locker->setLogger($logger); } private function deductBalance(float|int $amount) { if ($this->balance >= $amount) { // 模拟业务处理耗时 usleep(500 * 1000); $this->balance -= $amount; } return $this->balance; } /** * @return float */ private function getBalance(): float { return $this->balance; } public function runLock(int $i, string $type, float $amount) { try { $start = microtime(true); switch ($type) { case 'flock': $this->flock($amount); break; case 'redisLock': $this->redisLock($amount); break; case 'redLock': $this->redLock($amount); break; case 'channelLock': $this->channelLock($amount); break; case 'noMutex': default: $this->deductBalance($amount); break; } $balance = $this->getBalance(); $id = SwooleEngine::id(); $cost = microtime(true) - $start; $this->logger->notice('[{type} {cost}] ==> [{i}<=>{id}] ==> 当前用户的余额为:{balance}', compact('type', 'i', 'balance', 'id', 'cost')); return $balance; } catch (WiseLocksmithException|Throwable $e) { return sprintf('Err Msg: %s ====> %s', $e, $e->getPrevious()); } } private function flock(float $amount) { $path = BASE_PATH . '/runtime/alex.lock.cache'; $fileHandler = fopen($path, 'a+'); // fwrite($fileHandler, sprintf("%s - %s \r\n", 'Locked', microtime())); $res = $this->locker->flock($fileHandler, function () use ($amount) { return $this->deductBalance($amount); }); return $res; } private function redisLock(float $amount) { $res = $this->locker->redisLock('redisLock', function () use ($amount) { return $this->deductBalance($amount); }, 10); return $res; } private function redLock(float $amount) { $res = $this->locker->redLock('redLock', function () use ($amount) { return $this->deductBalance($amount); }, 10); return $res; } private function channelLock(float $amount) { $res = $this->locker->channelLock('channelLock', function () use ($amount) { return $this->deductBalance($amount); }); return $res; } }
When we access the /balance/consumer?type=noMutex URL, we can observe that the user's balance goes negative, which is clearly illogical. However, when we visit the following URLs, we can see that the user's balance is not going negative, demonstrating effective protection of the accuracy of shared resources in a race condition.
/balance/consumer?type=flock: File lock/balance/consumer?type=redisLock: Distributed lock/balance/consumer?type=redLock: Redlock/balance/consumer?type=channelLock: Coroutine-level mutex
Note
Regarding the use of redisLock and redLock:
- When using
redisLock, it defaults to using the firstkeyconfiguration in theconfig/autoload/redis.phpconfiguration file, which corresponds to the default Redis instance. You can optionally pass the fourth parameterstring|null $redisPoolNameto re-specify a different Redis instance as needed. - When using
redLock, it defaults to using all thekeyconfigurations in theconfig/autoload/redis.phpconfiguration file. You can optionally pass the fourth parameter?array $redisPoolNames = nullto re-specify different Redis instances as needed.
Documentation
You can find detailed documentation for pudongping/wise-locksmith.
Contributing
Bug reports (and small patches) can be submitted via the issue tracker. Forking the repository and submitting a Pull Request is preferred for substantial patches.
License
MIT, see LICENSE file.
pudongping/hyperf-wise-locksmith 适用场景与选型建议
pudongping/hyperf-wise-locksmith 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 7.2k 次下载、GitHub Stars 达 10, 最近一次更新时间为 2023 年 08 月 23 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「locking」 「lock」 「mutex」 「redlock」 「serialized」 「hyperf」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 pudongping/hyperf-wise-locksmith 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 pudongping/hyperf-wise-locksmith 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 pudongping/hyperf-wise-locksmith 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Redis distributed locks for laravel
CacheMutex for Yii2
Simple to use mutex implementation that can use flock, memcache, memcached, mysql or redis for locking
Wrapper for shared memory and locking functionality across different PHP extensions.
A Symfony bundle for Mutex implementation for PHP
Run mutually exclusive migrations from more than one server at a time
统计信息
- 总下载量: 7.2k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 10
- 点击次数: 30
- 依赖项目数: 3
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2023-08-23