symfony-lock 業(yè)務(wù)鎖

v2.0.0
版本
2022-09-18
版本更新時(shí)間
2914
安裝
2
star
為了后期更好的維護(hù),最新 2.0 版本已修改包名,請(qǐng)注意切換
webman-tech/symfony-lock
symfony/lock for webman
介紹
在 webman 中簡(jiǎn)化使用業(yè)務(wù)鎖功能
解決以下問題:
- 并發(fā)業(yè)務(wù)操作有時(shí)候需要鎖來(lái)防止并發(fā)導(dǎo)致的數(shù)據(jù)插入或更新問題
- 單獨(dú)使用
symfony/lock
時(shí)一般使用$factory->createLock('key')
,此時(shí) key 是一個(gè)字符串,不利于后期維護(hù)或多處使用
安裝
composer require webman-tech/symfony-lock
使用
定義一個(gè)自己的 Locker 類,比如:support\facade\Locker.php
,繼承 WebmanTech\SymfonyLock\Locker
然后在類上方加入注釋(用于代碼提示),舉例如下:
<?php
namespace support\facade;
use Symfony\Component\Lock\LockInterface;
/**
* @method static LockInterface order(?string $orderId = null, ?float $ttl = null, ?bool $autoRelease = null, ?string $prefix = null)
* @method static LockInterface changeCash(?string $userId = null, ?float $ttl = null, ?bool $autoRelease = null, ?string $prefix = null)
*/
class Locker extends \WebmanTech\SymfonyLock\Locker
{
}
業(yè)務(wù)中使用
<?php
namespace app\controller;
use support\facade\Locker;
class Cash {
public function changeCash()
{
$lock = Locker::cash($currentUserId);
if (!$lock->acquire()) {
throw new \Exception('操作太頻繁,請(qǐng)稍后再試');
}
try {
// 修改用戶金額
} finally {
$lock->release();
}
return 'ok';
}
}
更多操作參考:symfony/lock 文檔