<br /> private function lock(){<br /> $lock_name = "mb_lock";<br /> $memcache = new Memcache();<br /> $memcache->connect("127.0.0.1", 11211);<br /> $locked = $memcache->add($lock_name, 1, false, 30);<br /> if($locked){<br /> return true;<br /> }else{<br /> $wait = 1;<br /> while ($wait) {<br /> if(!$locked){<br /> usleep(rand(1,100)*1000);<br /> $locked = $memcache->add($lock_name, 1, false, 30);<br /> CakeLog::write("debug","wait:".$wait);<br /> $wait ;<br /> if($wait == 10){<br /> break;<br /> }<br /> }else{<br /> return true;<br /> }<br /> }<br /> }<br /> return $locked;<br /> }</p> <p> private function un_lock(){<br /> $lock_name = "mb_lock";<br /> $memcache = new <a href="http://www.cillap.com/">beste online casino</a> Memcache();<br /> $memcache->connect("127.0.0.1", 11211);<br /> return $memcache->delete($lock_name, 0);<br /> }</p> <p> function test(){<br /> $locked = $this->lock();<br /> if($locked){<br /> // usleep(1000*100);<br /> $this->loadModel("AbTest");<br /> $data = $this->AbTest->find("first",array("conditions"=>array("sold"=>0)));<br /> if(!empty($data)){<br /> $this->loadModel("AbAddTest");<br /> $this->AbAddTest->create();<br /> $this->AbAddTest->save(array("test_id"=>$data["AbTest"]["id"],"time"=>time()));<br /> $data["AbTest"]["sold"] = 1;<br /> $this->AbTest->save($data);<br /> }</p> <p> CakeLog::write("debug","success");<br /> echo "success";<br /> $this->un_lock();<br /> }else{<br /> echo "error";<br /> CakeLog::write("debug","success");<br /> }</p> <p> }<br />
<br /> home$ ab -n 1000 -c 10 http://local.www.xd.com/games/test<br />
在未使用memcache锁时,使用ab进行并发测试,会有很大几率出现重复数据的插入。
在使用memcache锁后,用ab进行并发测试,已经解决了上述问题