Skip to content

Instantly share code, notes, and snippets.

@codcodog
Last active August 7, 2019 03:26
Show Gist options
  • Save codcodog/1ba0fd863ce439bab50d1188e28d69f8 to your computer and use it in GitHub Desktop.
Save codcodog/1ba0fd863ce439bab50d1188e28d69f8 to your computer and use it in GitHub Desktop.
Redis setnx 实现分布式锁
/**
* 当前 cron 触发的进程获取 redis 锁
*
* 主要是防止在跑 cron 时,上一个 cron 计算尚没完成,
* 从而导致,重复执行计算的情况.
*
* 例如:1 * * * * 的定时任务,一分钟内计算未完成,
* 又再次触发,则会出现重复计算的混乱情况.
*
* @return bool
*/
protected function getLock()
{
$now = time();
$value = time() + self::TIMEOUT + 1;
$getLock = Redis::setnx(self::LOCK_KEY, $value);
if (! $getLock) {
$timeout = Redis::get(self::LOCK_KEY);
($timeout < $now) && Redis::getSet(self::LOCK_KEY, $value) < $now && $getLock = true;
}
return $getLock;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment