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.
55 lines
1.3 KiB
55 lines
1.3 KiB
<?php
|
|
declare(strict_types = 1);
|
|
|
|
namespace App\Utils\Traits;
|
|
|
|
use RedisException;
|
|
|
|
trait RedisLockUtil
|
|
{
|
|
|
|
/**
|
|
* 加锁
|
|
* @param string $lock_str 锁字符串
|
|
* @param int $expire_time 超时时间,默认300秒
|
|
* @return false|string
|
|
* @throws RedisException
|
|
*/
|
|
public function addLock(string $lock_str, int $expire_time = 300): bool|string
|
|
{
|
|
$redis = app('redis');
|
|
|
|
$unique_id = $this->getUniqueLockId();
|
|
$result = $redis->set($lock_str, $unique_id, 'ex', $expire_time, 'nx');
|
|
|
|
return $result ? $unique_id : false;
|
|
}
|
|
/**
|
|
* 解锁
|
|
* @param string $lock_str 锁字符串
|
|
* @param string $unique_id 唯一锁ID
|
|
* @return bool
|
|
* @throws RedisException
|
|
*/
|
|
public function unlock(string $lock_str, string $unique_id): bool
|
|
{
|
|
$redis = app('redis');
|
|
|
|
$redis->watch($lock_str);
|
|
if ($unique_id == $redis->get($lock_str)) {
|
|
$redis->multi()->del($lock_str)->exec();
|
|
return true;
|
|
}
|
|
$redis->unwatch();
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* 获取唯一锁ID
|
|
* @return string
|
|
*/
|
|
protected function getUniqueLockId(): string
|
|
{
|
|
return md5(uniqid((string)mt_rand(), true));
|
|
}
|
|
}
|
|
|