Using Memache in PHP as the operation class of the Process lock, phpmemache
<? Php // use Memache as the prefix of the Process lock class lock_processlock {// key protected $ sLockKeyPre; // Retry Interval protected $ iLockRetryInterval; // Number of Retries protected $ iLockRetryCount; // The lock expiration time protected $ iLockCacheTimeout; // The callback function protected $ onLockTimeoutFunc after the lock expires; // The memache instance protected $ oMemcache; // Number of Retries after memcache storage failure protected $ iMemcacheRetryCount; public function _ construct ($ onLockTimeoutFunc = NULL) {$ aLockConfig = get_config ('', 'Lock'); $ this-> sLockKeyPre = self: LOCK_KEY_PRE; $ this-> iLockRetryInterval = self: LOCK_RETRY_INTERVAL; $ this-> iLockRetryCount = self :: LOCK_RETRY_COUNT; $ this-> iLockCacheTimeout = self: LOCK_CACHE_TIMEOUT; $ this-> iMemcacheRetryCount = self: LOCK_CACHE_TIMEOUT; if (! $ OnLockTimeoutFunc) {// call the callback function if the lock fails. If no callback function is available, use $ onLockTimeoutFunc = 'onlocktimeout ';} $ this-> onLockTimeoutFunc = $ onLockTimeoutFunc;}/** connect to the memcache server */public function connect () {if (! Isset ($ this-> oMemcache) {$ this-> oMemcache = new Memcache (); $ this-> oMemcache-> connect ('123. 0.0.1 ', 11211);} return $ this-> oMemcache;}/* Add key */public addMemcache to MeMcache ($ sKey, $ sValue, $ iTimeout) {for ($ I = 0; $ I <$ this-> iMemcacheRetryCount) {$ bRes = $ this-> oMemcache-> add ($ sKey, $ sValue, $ iTimeout ); if ($ bRes) {return true;} // if the lock fails, after sleep, lock usleep ($ this-> iLockRetryInterval * 1000);} return false ;} /* lock */public function lock ($ sLockID) {$ oMemcache = $ this-> connect (); $ sKey = $ this-> sLockKeyPre. $ sLockID; // you can try it multiple times if the lock fails ($ I = 0; $ I <$ this-> iLockRetryCount; $ I ++) {// here, you can set the value if ($ this-> addMemcache ($ sKey, '1', $ this-> iLockCacheTimeout) {return true ;} // If the lock fails, after sleep, apply the new usleep lock ($ this-> iLockRetryInterval * 1000);} // If the lock fails, call the callback function ,. that is, the operation if (is_callable ($ this-> onLockTimeoutFunc) to be processed after the failure) {// call the call_user_func function ($ this-> onLockTimeoutFunc );}} /* unlock operation */public function unlock ($ sLockID) {$ oMemcache = $ this-> connect (); $ sKey = $ this-> sLockKeyPre. $ sLockID; // delete keyreturn $ this-> oMemcache-> delete ($ sKey);}/** if the lock fails, perform the following operations */public function onLockTimeout () {echo ("lock timeout") ;}// application instance $ oLock = new lock_processlock (); $ lockResource = "test "; // lock $ oLock-> lock ($ lockResource); // unlock $ oLock-> unlock ($ lockResource );