Original address
The Memcache::add () method in Memcache key
key
stores a variable var
to the cache server as a key when it does not exist before the cache server. We use Add to add a key-value correspondence to the server, and if it succeeds, it means that there is another concurrency job in operation. Use the atom of add to determine if you want to execute the hotspot code. The specific code should be combined with the previous PHP use Memcache. Using this method to control concurrency requires taking into account the validity period of the cache and the memory-based characteristics of the cache.
Implement a class cachelock that contains locks, unlocks, lock-state checks:
classcachelock{ConstKey_prefix = ' _lock '; Private $MC; Public function__construct () {$this->MC =NewDlufmemcache (' 127.0.0.1 ', 11211); } /** * for lock operation * @param [type] $lock _id * @param integer $expire*/ Public functionLock ($lock _id,$expire=5){ $mkey= Self::key_prefix.$lock _id; for($i= 0;$i< 10;$i++){ $flag=false; Try{ $flag=$this->mc->add ($mkey, ' 1 ',$expire); }Catch(Exception $e){ $flag=false; //Log } if($flag){ return true; }Else{ //wait for 0.3 seconds Usleep(300000); } } return false; } /** * Determine lock status * @param [type] $lock _id * @return Boolean*/ Public functionIslock ($lock _id){ $mkey= Self::key_prefix.$lock _id; $ret=$this->mc->get ($mkey); if(Empty($ret) ||$ret===false){ return false; } return true; } /** * unlock * @param [type] $lock _id * @return [type]*/ Public functionUnLock ($lock _id){ $mkey= Self::key_prefix.$lock _id; $ret=$this->mc->delete ($mkey); return $ret; } }
Then use Cachelock for concurrency hotspot code control
function Uselock () { $lockobjnew cachelock (); $lock $lockobj->lock (' Cachelock '); if (! $lock { echo "Cachelock is lock"; return ; } /* The Hot code is written here * /$lockobj->unlock (' Cachelock ');}
System schema cache Memcache uses atomic action Add to implement concurrent locks