Last active
August 7, 2019 03:26
-
-
Save codcodog/1ba0fd863ce439bab50d1188e28d69f8 to your computer and use it in GitHub Desktop.
Redis setnx 实现分布式锁
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 当前 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