[System architecture] cache MEMCACHE uses atomic operation add to implement concurrency lock and memcacheadd
Original article address
MemcacheMemcache: add ()Method does not exist before the Cache Serverkey
Tokey
Store a variable as a keyvar
To the cache server. We use add to add a key-value correspondence to the server. If it is successfully added, otherwise another concurrent job is being operated. The atomicity of add is used to determine whether hotspot code is to be executed. The specific code should be combined with the previous php to use memcache. To use this method to control concurrency, you must consider the cache validity period and memory-based Cache features.
Implement a class cacheLock that includes lock, unlock, and lock status check:
Class cacheLock {const KEY_PREFIX = '_ lock'; private $ mc; public function _ construct () {$ this-> mc = new dlufMemcache ('123. 0.0.1 ', 11211);}/*** Lock operation * @ param [type] $ lock_id * @ param integer $ expire */public function Lock ($ 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 the lock status * @ param [type] $ lock_id * @ return boolean */public function isLock ($ 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 function unLock ($ lock_id) {$ mkey = self :: KEY_PREFIX. $ lock_id; $ ret = $ this-> mc-> delete ($ mkey); return $ ret ;}}
Then use cacheLock to control concurrent hotspot code
Function useLock () {$ lockobj = new cacheLock (); $ lock = $ lockobj-> Lock ('cachelock '); if (! $ Lock) {echo "cachelock is lock"; return;}/* hotspot code written here */$ lockobj-> unLock ('cachelock ');}