?php
//高并發(fā)分布式鎖
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("系統(tǒng)繁忙"."\n");
}
function writeFile($data,$type='a'){
//sleep(1);
//usleep(500000);//假設(shè)暫停 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);
}
如果一個請求更新緩存的時間比較長,甚至比鎖的有效期還要長,導(dǎo)致在緩存更新過程中,鎖就失效了,此時另一個請求會獲取鎖,但前一個請求在緩存更新完畢的時候,如果不加以判斷直接刪除鎖,就會出現(xiàn)誤刪除其它請求創(chuàng)建的鎖的情況,所以我們在創(chuàng)建鎖的時候需要引入一個隨機值:
$ok = $redis->set($key, $random, array('nx', 'ex' =>5));
if ($ok) {
$cache->update();
if ($redis->get($key) == $random) {
$redis->del($key);
}
}