?php
//高并发分布式锁
header("Content-type:text/html;charset=utf-8");
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
echo "Connection to server sucessfully";
//echo $redis->get("name");exit;
$expire = 1;
$key = 'test1';
$lock = false;
$is_lock=$redis->setnx($key,time()+$expire);
if(!$is_lock){
$lock_time=$redis->get($key);
//锁已过期,重置
if($lock_timetime()){
$redis->del($key);
$lock_time=$redis->get($key);
$is_lock=$redis->setnx($key,time()+$expire);
}
}
$is_lock ? true : false;
if($is_lock){
writeFile("正常访问"."\n");
}else{
writeFile("系统繁忙"."\n");
}
function writeFile($data,$type='a'){
//sleep(1);
//usleep(500000);//假设暂停 500毫秒
$filename = date("Ymd").".log";
$handle =@ fopen($filename, $type);
flock($handle, LOCK_EX);
ob_start();
echo "\n" . "[SQL]" . "\n";
print_r ($data);
$string = ob_get_contents();
ob_end_clean();
$fettle = @fwrite($handle, $string);
fclose($handle);
@chmod($filename,0777);
}
如果一个请求更新缓存的时间比较长,甚至比锁的有效期还要长,导致在缓存更新过程中,锁就失效了,此时另一个请求会获取锁,但前一个请求在缓存更新完毕的时候,如果不加以判断直接删除锁,就会出现误删除其它请求创建的锁的情况,所以我们在创建锁的时候需要引入一个随机值:
$ok = $redis->set($key, $random, array('nx', 'ex' =>5));
if ($ok) {
$cache->update();
if ($redis->get($key) == $random) {
$redis->del($key);
}
}