php 高并发 memcache 锁

<br />
	private function lock(){<br />
		$lock_name = "mb_lock";<br />
		$memcache = new Memcache();<br />
		$memcache-&gt;connect("127.0.0.1", 11211);<br />
		$locked = $memcache-&gt;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-&gt;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-&gt;connect("127.0.0.1", 11211);<br />
		return $memcache-&gt;delete($lock_name, 0);<br />
	}</p>
<p>	function test(){<br />
		$locked = $this-&gt;lock();<br />
		if($locked){<br />
			// usleep(1000*100);<br />
			$this-&gt;loadModel("AbTest");<br />
			$data = $this-&gt;AbTest-&gt;find("first",array("conditions"=&gt;array("sold"=&gt;0)));<br />
			if(!empty($data)){<br />
				$this-&gt;loadModel("AbAddTest");<br />
				$this-&gt;AbAddTest-&gt;create();<br />
				$this-&gt;AbAddTest-&gt;save(array("test_id"=&gt;$data["AbTest"]["id"],"time"=&gt;time()));<br />
				$data["AbTest"]["sold"] = 1;<br />
				$this-&gt;AbTest-&gt;save($data);<br />
			}</p>
<p>			CakeLog::write("debug","success");<br />
			echo &quot;success&quot;;<br />
			$this-&gt;un_lock();<br />
		}else{<br />
			echo &quot;error&quot;;<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进行并发测试,已经解决了上述问题

发表评论