承接 pudongping/hyperf-wise-locksmith 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

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

Latest Stable Version Total Downloads Latest Unstable Version Minimum PHP Version Packagist License

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 first key configuration in the config/autoload/redis.php configuration file, which corresponds to the default Redis instance. You can optionally pass the fourth parameter string|null $redisPoolName to re-specify a different Redis instance as needed.
  • When using redLock, it defaults to using all the key configurations in the config/autoload/redis.php configuration file. You can optionally pass the fourth parameter ?array $redisPoolNames = null to 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 我们能提供哪些服务?
定制开发 / 二次开发

基于 pudongping/hyperf-wise-locksmith 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 7.2k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 10
  • 点击次数: 30
  • 依赖项目数: 3
  • 推荐数: 0

GitHub 信息

  • Stars: 10
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-08-23