Skip to content

Instantly share code, notes, and snippets.

@sy-records
Created December 24, 2019 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sy-records/88d8ab72724857294aef048d08a807ff to your computer and use it in GitHub Desktop.
Save sy-records/88d8ab72724857294aef048d08a807ff to your computer and use it in GitHub Desktop.
PHP使用Redis防止大并发下二次写入
<?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