Redis分布式鎖

RedisLockClass.php

<?php
/**
 *在redis上實現(xiàn)分布式鎖
 */
class RedisLock {
    private $redisString;
    private $lockedNames = [];

    public function __construct($param = NULL) {
        $this->redisString = RedisFactory::get($param)->string;
    }

    /**
     * 加鎖
     * @param  [type]  $name           鎖的標(biāo)識名
     * @param  integer $timeout        循環(huán)獲取鎖的等待超時時間洒敏,在此時間內(nèi)會一直嘗試獲取鎖直到超時堕澄,為0表示失敗后直接返回不等待
     * @param  integer $expire         當(dāng)前鎖的最大生存時間(秒),必須大于0,如果超過生存時間鎖仍未被釋放,則系統(tǒng)會自動強(qiáng)制釋放
     * @param  integer $waitIntervalUs 獲取鎖失敗后掛起再試的時間間隔(微秒)
     * @return [type]                  [description]
     */
    public function lock($name, $timeout = 0, $expire = 15, $waitIntervalUs = 100000) {
        if ($name == null) return false;

        //取得當(dāng)前時間
        $now = time();
        //獲取鎖失敗時的等待超時時刻
        $timeoutAt = $now + $timeout;
        //鎖的最大生存時刻
        $expireAt = $now + $expire;

        $redisKey = "Lock:{$name}";
        while (true) {
            //將rediskey的最大生存時刻存到redis里,過了這個時刻該鎖會被自動釋放
            $result = $this->redisString->setnx($redisKey, $expireAt);

            if ($result != false) {
                //設(shè)置key的失效時間
                $this->redisString->expire($redisKey, $expireAt);
                //將鎖標(biāo)志放到lockedNames數(shù)組里
                $this->lockedNames[$name] = $expireAt;
                return true;
            }

            //以秒為單位,返回給定key的剩余生存時間
            $ttl = $this->redisString->ttl($redisKey);

            //ttl小于0 表示key上沒有設(shè)置生存時間(key是不會不存在的奈籽,因為前面setnx會自動創(chuàng)建)
            //如果出現(xiàn)這種狀況,那就是進(jìn)程的某個實例setnx成功后 crash 導(dǎo)致緊跟著的expire沒有被調(diào)用
            //這時可以直接設(shè)置expire并把鎖納為己用
            if ($ttl < 0) {
                $this->redisString->set($redisKey, $expireAt);
                $this->lockedNames[$name] = $expireAt;
                return true;
            }

            /*****循環(huán)請求鎖部分*****/
            //如果沒設(shè)置鎖失敗的等待時間 或者 已超過最大等待時間了鸵赫,那就退出
            if ($timeout <= 0 || $timeoutAt < microtime(true)) break;

            //隔 $waitIntervalUs 后繼續(xù) 請求
            usleep($waitIntervalUs);

        }

        return false;
    }

    /**
     * 解鎖
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    public function unlock($name) {
        //先判斷是否存在此鎖
        if ($this->isLocking($name)) {
            //刪除鎖
            if ($this->redisString->deleteKey("Lock:$name")) {
                //清掉lockedNames里的鎖標(biāo)志
                unset($this->lockedNames[$name]);
                return true;
            }
        }
        return false;
    }

    /**
     * 釋放當(dāng)前所有獲得的鎖
     * @return [type] [description]
     */
    public function unlockAll() {
        //此標(biāo)志是用來標(biāo)志是否釋放所有鎖成功
        $allSuccess = true;
        foreach ($this->lockedNames as $name => $expireAt) {
            if (false === $this->unlock($name)) {
                $allSuccess = false;    
            }
        }
        return $allSuccess;
    }

    /**
     * 給當(dāng)前所增加指定生存時間衣屏,必須大于0
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    public function expire($name, $expire) {
        //先判斷是否存在該鎖
        if ($this->isLocking($name)) {
            //所指定的生存時間必須大于0
            $expire = max($expire, 1);
            //增加鎖生存時間
            if ($this->redisString->expire("Lock:$name", $expire)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判斷當(dāng)前是否擁有指定名字的所
     * @param  [type]  $name [description]
     * @return boolean       [description]
     */
    public function isLocking($name) {
        //先看lonkedName[$name]是否存在該鎖標(biāo)志名
        if (isset($this->lockedNames[$name])) {
            //從redis返回該鎖的生存時間
            return (string)$this->lockedNames[$name] = (string)$this->redisString->get("Lock:$name");
        }

        return false;
    }

}

RedisQueueClass.php

<?php
/**
 * 任務(wù)隊列
 * 
 */
class RedisQueue {
    private $_redis;

    public function __construct($param = null) {
        $this->_redis = RedisFactory::get($param);
    }

    /**
     * 入隊一個 Task
     * @param  [type]  $name          隊列名稱
     * @param  [type]  $id            任務(wù)id(或者其數(shù)組)
     * @param  integer $timeout       入隊超時時間(秒)
     * @param  integer $afterInterval [description]
     * @return [type]                 [description]
     */
    public function enqueue($name, $id, $timeout = 10, $afterInterval = 0) {
        //合法性檢測
        if (empty($name) || empty($id) || $timeout <= 0) return false;

        //加鎖
        if (!$this->_redis->lock->lock("Queue:{$name}", $timeout)) {
            Logger::get('queue')->error("enqueue faild becouse of lock failure: name = $name, id = $id");
            return false;
        }
        
        //入隊時以當(dāng)前時間戳作為 score
        $score = microtime(true) + $afterInterval;
        //入隊
        foreach ((array)$id as $item) {
            //先判斷下是否已經(jīng)存在該id了
            if (false === $this->_redis->zset->getScore("Queue:$name", $item)) {
                $this->_redis->zset->add("Queue:$name", $score, $item);
            }
        }
        
        //解鎖
        $this->_redis->lock->unlock("Queue:$name");

        return true;

    }

    /**
     * 出隊一個Task,需要指定$id 和 $score
     * 如果$score 與隊列中的匹配則出隊辩棒,否則認(rèn)為該Task已被重新入隊過狼忱,當(dāng)前操作按失敗處理
     * 
     * @param  [type]  $name    隊列名稱 
     * @param  [type]  $id      任務(wù)標(biāo)識
     * @param  [type]  $score   任務(wù)對應(yīng)score,從隊列中獲取任務(wù)時會返回一個score一睁,只有$score和隊列中的值匹配時Task才會被出隊
     * @param  integer $timeout 超時時間(秒)
     * @return [type]           Task是否成功藕赞,返回false可能是redis操作失敗,也有可能是$score與隊列中的值不匹配(這表示該Task自從獲取到本地之后被其他線程入隊過)
     */
    public function dequeue($name, $id, $score, $timeout = 10) {
        //合法性檢測
        if (empty($name) || empty($id) || empty($score)) return false;
        
        //加鎖
        if (!$this->_redis->lock->lock("Queue:$name", $timeout)) {
            Logger:get('queue')->error("dequeue faild becouse of lock lailure:name=$name, id = $id");
            return false;
        }
        
        //出隊
        //先取出redis的score
        $serverScore = $this->_redis->zset->getScore("Queue:$name", $id);
        $result = false;
        //先判斷傳進(jìn)來的score和redis的score是否是一樣
        if ($serverScore == $score) {
            //刪掉該$id
            $result = (float)$this->_redis->zset->delete("Queue:$name", $id);
            if ($result == false) {
                Logger::get('queue')->error("dequeue faild because of redis delete failure: name =$name, id = $id");
            }
        }
        //解鎖
        $this->_redis->lock->unlock("Queue:$name");

        return $result;
    }

    /**
     * 獲取隊列頂部若干個Task 并將其出隊
     * @param  [type]  $name    隊列名稱
     * @param  integer $count   數(shù)量
     * @param  integer $timeout 超時時間
     * @return [type]           返回數(shù)組[0=>['id'=> , 'score'=> ], 1=>['id'=> , 'score'=> ], 2=>['id'=> , 'score'=> ]]
     */
    public function pop($name, $count = 1, $timeout = 10) {
        //合法性檢測
        if (empty($name) || $count <= 0) return []; 
        
        //加鎖
        if (!$this->_redis->lock->lock("Queue:$name")) {
            Logger::get('queue')->error("pop faild because of pop failure: name = $name, count = $count");
            return false;
        }
        
        //取出若干的Task
        $result = [];
        $array = $this->_redis->zset->getByScore("Queue:$name", false, microtime(true), true, false, [0, $count]);

        //將其放在$result數(shù)組里 并 刪除掉redis對應(yīng)的id
        foreach ($array as $id => $score) {
            $result[] = ['id'=>$id, 'score'=>$score];
            $this->_redis->zset->delete("Queue:$name", $id);
        }

        //解鎖
        $this->_redis->lock->unlock("Queue:$name");

        return $count == 1 ? (empty($result) ? false : $result[0]) : $result;
    }

    /**
     * 獲取隊列頂部的若干個Task
     * @param  [type]  $name  隊列名稱
     * @param  integer $count 數(shù)量
     * @return [type]         返回數(shù)組[0=>['id'=> , 'score'=> ], 1=>['id'=> , 'score'=> ], 2=>['id'=> , 'score'=> ]]
     */
    public function top($name, $count = 1) {
        //合法性檢測
        if (empty($name) || $count < 1)  return [];

        //取錯若干個Task
        $result = [];
        $array = $this->_redis->zset->getByScore("Queue:$name", false, microtime(true), true, false, [0, $count]);
        
        //將Task存放在數(shù)組里
        foreach ($array as $id => $score) {
            $result[] = ['id'=>$id, 'score'=>$score];
        }

        //返回數(shù)組 
        return $count == 1 ? (empty($result) ? false : $result[0]) : $result;       
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末卖局,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子双霍,更是在濱河造成了極大的恐慌砚偶,老刑警劉巖批销,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異染坯,居然都是意外死亡均芽,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進(jìn)店門单鹿,熙熙樓的掌柜王于貴愁眉苦臉地迎上來掀宋,“玉大人,你說我怎么就攤上這事仲锄【⒚睿” “怎么了?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵儒喊,是天一觀的道長镣奋。 經(jīng)常有香客問我,道長怀愧,這世上最難降的妖魔是什么侨颈? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮芯义,結(jié)果婚禮上哈垢,老公的妹妹穿的比我還像新娘。我一直安慰自己扛拨,他們只是感情好耘分,可當(dāng)我...
    茶點故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著鬼癣,像睡著了一般陶贼。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上待秃,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天拜秧,我揣著相機(jī)與錄音,去河邊找鬼章郁。 笑死枉氮,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的暖庄。 我是一名探鬼主播聊替,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼培廓!你這毒婦竟也來了惹悄?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤肩钠,失蹤者是張志新(化名)和其女友劉穎泣港,沒想到半個月后暂殖,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡当纱,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年呛每,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片坡氯。...
    茶點故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡晨横,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出箫柳,到底是詐尸還是另有隱情手形,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布滞时,位于F島的核電站叁幢,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏坪稽。R本人自食惡果不足惜曼玩,卻給世界環(huán)境...
    茶點故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望窒百。 院中可真熱鬧黍判,春花似錦、人聲如沸篙梢。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽渤滞。三九已至贬墩,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間妄呕,已是汗流浹背陶舞。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留绪励,地道東北人肿孵。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像疏魏,于是被迫代替她去往敵國和親停做。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,086評論 2 355

推薦閱讀更多精彩內(nèi)容