Created
December 24, 2019 03:28
-
-
Save sy-records/88d8ab72724857294aef048d08a807ff to your computer and use it in GitHub Desktop.
PHP使用Redis防止大并发下二次写入
This file contains 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
<?php | |
$lock_key = 'LOCK_PREFIX_'. $key; | |
$is_lock = $redis->setNX($lock_key, 1); // 加锁 | |
if ($is_lock == true) {// 获取锁权限 | |
// ... 具体操作 | |
// 释放锁 | |
$redis->del($lock_key); | |
return true; | |
} else { | |
//usleep(100000); | |
// 防止死锁 | |
if ($redis->ttl($lock_key) == -1) { | |
$redis->expire($lock_key, 5); | |
} | |
// 获取不到锁权限,直接返回 | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment