PHP中使用Memache作為進(jìn)程鎖的操作類分享

字號:


    這篇文章主要介紹了PHP中使用Memache作為進(jìn)程鎖的操作類分享,本文直接給出類實現(xiàn)代碼以及應(yīng)用示例,需要的朋友可以參考下
    <?php
    // 使用Memache 作為進(jìn)程鎖
    class lock_processlock{
    // key 的前綴
    protected $sLockKeyPre;
    // 重試間隔
    protected $iLockRetryInterval;
    //重試次數(shù)
    protected $iLockRetryCount;
    //鎖的過期時間
    protected $iLockCacheTimeout;
    // 鎖過期后的回調(diào)函數(shù)
    protected $onLockTimeoutFunc;
    // memache 的實例
    protected $oMemcache;
    // 存儲memcache失敗后重試次數(shù)
    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){
    // 如果加鎖不成功則調(diào)用回調(diào)函數(shù),如果沒有回調(diào)函數(shù),使用本類中所帶的
    $onLockTimeoutFunc ='onLockTimeout' ;
    }
    $this->onLockTimeoutFunc = $onLockTimeoutFunc;
    }
    /**
    連接memcache 服務(wù)器
    */
    public function connect() {
    if (! isset ( $this->oMemcache )) {
    $this->oMemcache = new Memcache ();
    $this->oMemcache->connect ( '127.0.0.1', 11211 );
    }
    return $this->oMemcache;
    }
    /*
    向MeMcache中添加 key
    */
    public addMemcache($sKey, $sValue, $iTimeout){
    for($i= 0 ; $i<$this->iMemcacheRetryCount){
    $bRes = $this->oMemcache->add($sKey, $sValue, $iTimeout);
    if($bRes){
    return true ;
    }
    // 如果加鎖不成功,sleep 之后,從新加鎖
    usleep($this->iLockRetryInterval*1000);
    }
    return false ;
    }
    /*
    加鎖
    */
    public function lock($sLockID){
    $oMemcache = $this->connect();
    $sKey = $this->sLockKeyPre . $sLockID;
    // 加鎖如果不成功可以多試幾次
    for($i = 0 ; $i <$this->iLockRetryCount ; $i++){
    // 這里設(shè)置value 的值可以隨便設(shè)置
    if($this->addMemcache($sKey,'1',$this->iLockCacheTimeout)){
    return true ;
    }
    // 如果加鎖不成功,sleep 之后,從新加鎖
    usleep($this->iLockRetryInterval*1000);
    }
    // 若還不成功,則加鎖失敗,調(diào)用回調(diào)函數(shù),.也就是失敗后需要處理的操作
    if(is_callable($this->onLockTimeoutFunc)){
    // 調(diào)用函數(shù)
    call_user_func($this->onLockTimeoutFunc);
    }
    }
    /*
    解鎖操作
    */
    public function unlock($sLockID){
    $oMemcache = $this->connect();
    $sKey = $this->sLockKeyPre . $sLockID;
    // 刪除key
    return $this->oMemcache->delete($sKey);
    }
    /**
    如果加鎖不成功,則執(zhí)行如下操作
    */
    public function onLockTimeout(){
    echo ("加鎖超時");
    }
    }
    // 應(yīng)用實例
    $oLock = new lock_processlock();
    $lockResource = "test";
    // 加鎖
    $oLock->lock($lockResource);
    // 解鎖