php redis setnx分布式锁简单原理解析
我就废话不多说了,大家还是直接看代码吧~
<?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_time<time()){ $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); }
补充知识:php redis set 单机锁
如果一个请求更新缓存的时间比较长,甚至比锁的有效期还要长,导致在缓存更新过程中,锁就失效了,此时另一个请求会获取锁,但前一个请求在缓存更新完毕的时候,如果不加以判断直接删除锁,就会出现误删除其它请求创建的锁的情况,所以我们在创建锁的时候需要引入一个随机值:
$ok = $redis->set($key, $random, array('nx', 'ex' =>5)); if ($ok) { $cache->update(); if ($redis->get($key) == $random) { $redis->del($key); } }
相关推荐
smartbaby 2020-11-11
夙梦流尘 2020-09-23
峰哥 2020-09-23
王道革 2020-11-25
wangdonghello 2020-11-03
Langeldep 2020-11-16
chenhualong0 2020-11-16
聚合室 2020-11-16
koushr 2020-11-12
MRFENGG 2020-11-11
guoyanga 2020-11-10
fackyou00 2020-11-10
Orangesss 2020-11-03
dongCSDN 2020-10-31
rainandtear 2020-10-30
Quietboy 2020-10-30
liuyulong 2020-10-29
fansili 2020-10-29
温攀峰 2020-10-23