Hyperf 分布式锁
上代码
<?php
namespace App\Support;
use Hyperf\Redis\Redis;
class RedisDistributedLock
{
/**
* @var Redis
*/
private Redis $redis;
/**
* 锁的名称
* @var string
*/
private string $lockKey;
/**
* 锁的超时时间,单位:毫秒
* @var int
*/
private int $lockTimeout;
/**
* 加锁成功后的锁值,用于释放锁
* @var string
*/
private string $lockValue;
/**
* @param Redis $redis
* @param string $lockKey
* @param int $lockTimeout
*/
public function __construct(Redis $redis, string $lockKey, int $lockTimeout)
{
$this->redis = $redis;
$this->lockKey = $lockKey;
$this->lockTimeout = $lockTimeout;
}
/**
* 获取锁
* @return bool
*/
public function lock(): bool
{
// 获取锁的值
$this->lockValue = uniqid();
// 尝试获取锁
$isLocked = $this->redis->set($this->lockKey, $this->lockValue, ['NX', 'PX' => $this->lockTimeout]);
return (bool)$isLocked;
}
/**
* 释放锁
* @return void
*/
public function release(): void
{
$script = <<<LUA
if redis.call('get', KEYS[1]) == ARGV[1] then
return redis.call('del', KEYS[1])
else
return 0
end
LUA;
$this->redis->eval($script, [$this->lockKey, $this->lockValue], 1);
}
}
使用示例
use App\Model\DistributedLock;
$redis = new Redis(...);
$lock = new DistributedLock($redis, 'lock_key', 10000);
if ($lock->lock()) {
try {
// 执行临界区代码
} finally {
$lock->release();
}
} else {
// 获取锁失败
}
以上是使用 chatGPT 生成的,太牛了!!!
本作品采用《CC 协议》,转载必须注明作者和本文链接