高并发下redis使用nx sex命令和lua脚本分别实现分布式锁
使用nx,ex实现
//调用
$lockValue = app(RedisService::class)->setLock($lockKey, 120); //120s最多处理一次
if (!$lockValue) {
return [];
}
/**
* 设置锁
* User: kudaren
* Date: 2023/12/31 4:57 下午
*
* @param $key
* @param int $ttl
* @return string
*/
public function setLock($key, $ttl = 2, $flag = 'ex')
{
mt_srand();
$uniKey = uniqid() . mt_rand(1000, 9999);
$isOk = $this->redis->set($key, $uniKey, ['nx', $flag => $ttl]);
if (!$isOk) {
return '';
} else {
return $uniKey;
}
}
使用lua脚本
//调用
$lockValue = $this->redisDistributedLock->getLock($key, true);
if (!$lockValue) {
return 'error';
}
/**
* 获取锁
* @param string $key
* @param bool $isBLock 是否阻塞,阻塞状态下每隔一定间隔重试,超过2秒后还没有获取到锁返回失败
* @return bool
*/
public function getLock($key, $isBLock = false)
{
//KEYS为键名参数,ARGV为附加参数
//eval第2个参数指定键名参数的个数
//redis ttl命令说明:当key不存在时返回-2,当key存在但没有设置剩余生存时间时返回-1,否则返回key的剩余生存时间(毫秒)。
$lua = <<<EOF
local key = KEYS[1]
local value = ARGV[1]
local ttl = ARGV[2]
if (redis.call('setnx', key, value) == 1)
then
return redis.call('expire', key, ttl)
elseif (redis.call('ttl', key) == -1)
then
return redis.call('expire', key, ttl)
end
return 0
EOF;
$value = uniqid() . mt_rand(1000, 9999);
$res = $this->redis->eval($lua, [$key, $value, self::$ttl], 1);
if ($res) {
return $value;
} else {
if ($isBLock) {
$startTime = time();
while (true) {
$res = $this->redis->eval($lua, [$key, $value, self::$ttl], 1);
if ($res) {
return $value;
} else {
usleep(250000);
if (time() - $startTime >= 2) {
return false;
}
}
}
} else {
return false;
}
}
}