You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.7 KiB
62 lines
1.7 KiB
<?php
|
|
declare(strict_types = 1);
|
|
|
|
namespace App\Utils\Traits;
|
|
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Facades\Redis;
|
|
use Illuminate\Support\Str;
|
|
|
|
trait RedisLockUtil
|
|
{
|
|
|
|
/**
|
|
* 加锁
|
|
* @param string $lock_str 锁字符串
|
|
* @param int $expire_time 超时时间,默认300秒
|
|
* @return bool|string
|
|
*/
|
|
public function addLock(string $lock_str, int $expire_time = 300): bool|string
|
|
{
|
|
try {
|
|
$unique_id = $this->getUniqueLockId();
|
|
$result = Redis::set($lock_str, $unique_id, 'ex', $expire_time, 'nx');
|
|
|
|
return $result ? $unique_id : false;
|
|
} catch (\Exception $e) {
|
|
Log::channel('genera_error')->error("Error while acquiring lock for {$lock_str}: " . $e->getMessage());
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 解锁
|
|
* @param string $lock_str 锁字符串
|
|
* @param string $unique_id 唯一锁ID
|
|
* @return bool
|
|
*/
|
|
public function unlock(string $lock_str, string $unique_id): bool
|
|
{
|
|
try {
|
|
Redis::watch($lock_str);
|
|
if (Redis::exists($lock_str) && $unique_id == Redis::get($lock_str)) {
|
|
Redis::multi()->del($lock_str)->exec();
|
|
return true;
|
|
}
|
|
Redis::unwatch();
|
|
return false;
|
|
} catch (\Exception $e) {
|
|
Log::channel('genera_error')->error("Error while releasing lock for {$lock_str}: " . $e->getMessage());
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取唯一锁ID
|
|
* @return string
|
|
*/
|
|
protected function getUniqueLockId(): string
|
|
{
|
|
return Str::uuid()->toString();
|
|
}
|
|
}
|
|
|