使用redis实现分布式锁
lock类
class RedisLock
{
protected $redis;
public function __construct($redis)
{
$this->redis = $redis;
}
public function getLock($key, $lockTime = 3)
{
return $this->redis->set($key, 1, ['EX' => $lockTime, 'NX']);
}
public function release($key)
{
return $this->redis->del($key);
}
}
锁运用
$redis = new \redis();
$redis->connect("127.0.0.1", 6379);
$lock = new RedisLock($redis);
// 获取锁
$isLock = $lock->getLock("lock_test");
if (!$isLock) {
throw new \Exception("业务繁忙,请稍后再试");
}
// 业务逻辑
// 可以写在 finally 中,防止业务逻辑抛出异常,没有释放锁
$lock->release();