class RedisLock
{
protected $redis;
protected $lockKey;
protected $timeout;
public function __construct(Redis $redis, $key, $timeout = 5)
{
$this->redis = $redis;
$this->lockKey = $key;
$this->timeout = $timeout;
}
public function lock()
{
$luaScript = "
if redis.call('setnx', KEYS[1], 1) == 1 then
redis.call('expire', KEYS[1], ARGV[1])
return true
else
return false
end
";
$result = $this->redis->eval($luaScript, [$this->lockKey, $this->timeout]);
return boolval($result);
}
public function unlock()
{
$this->redis->del($this->lockKey);
}
}
使用方法
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$lock = new RedisLock($redis, 'my_lock_key');
if ($lock->lock()) {
// 获取锁成功,执行业务逻辑
$lock->unlock();
} else {
// 获取锁失败,执行其他逻辑
}
虽然Redis分布式锁是常用的分布式锁实现方式之一,但是需要注意它的可靠性问题。因为Redis是一个单进程单线程的程序,所以在高并发的情况下,Redis可能会出现瓶颈。此外,Redis分布式锁还可能存在死锁和误删的风险,需要一些额外的防范和处理措施。