Skip to content

Instantly share code, notes, and snippets.

@guiqide
Created December 29, 2018 03:32
Show Gist options
  • Save guiqide/77809c831f0bf555dec89e0c5ec3b522 to your computer and use it in GitHub Desktop.
Save guiqide/77809c831f0bf555dec89e0c5ec3b522 to your computer and use it in GitHub Desktop.
增加分布锁,支持等待锁
/**
* 加锁——允许设置最长等待时间,单位秒
* 在等待期内持续争锁
*/
private function __addRedlock($expire = 3)
{
$time = time();
$lock = null;
do {
$lock = Redis::set("{$this->redisKey}_redlock", true, 'ex', 1, 'nx');
if (!$lock) { // 等待20毫秒
usleep(1000 * 20);
}
} while (!$lock && $time + $expire < time());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment