麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 數(shù)據(jù)庫 > Redis > 正文

基于Redis實(shí)現(xiàn)分布式鎖以及任務(wù)隊(duì)列

2020-03-17 12:41:30
字體:
供稿:網(wǎng)友
這篇文章主要介紹了基于Redis實(shí)現(xiàn)分布式鎖以及任務(wù)隊(duì)列,需要的朋友可以參考下
 

一、前言

  雙十一剛過不久,大家都知道在天貓、京東、蘇寧等等電商網(wǎng)站上有很多秒殺活動,例如在某一個(gè)時(shí)刻搶購一個(gè)原價(jià)1999現(xiàn)在秒殺價(jià)只要999的手機(jī)時(shí),會迎來一個(gè)用戶請求的高峰期,可能會有幾十萬幾百萬的并發(fā)量,來搶這個(gè)手機(jī),在高并發(fā)的情形下會對數(shù)據(jù)庫服務(wù)器或者是文件服務(wù)器應(yīng)用服務(wù)器造成巨大的壓力,嚴(yán)重時(shí)說不定就宕機(jī)了,另一個(gè)問題是,秒殺的東西都是有量的,例如一款手機(jī)只有10臺的量秒殺,那么,在高并發(fā)的情況下,成千上萬條數(shù)據(jù)更新數(shù)據(jù)庫(例如10臺的量被人搶一臺就會在數(shù)據(jù)集某些記錄下 減1),那次這個(gè)時(shí)候的先后順序是很亂的,很容易出現(xiàn)10臺的量,搶到的人就不止10個(gè)這種嚴(yán)重的問題。那么,以后所說的問題我們該如何去解決呢?

       接下來我所分享的技術(shù)就可以拿來處理以上的問題: 分布式鎖 和 任務(wù)隊(duì)列

二、實(shí)現(xiàn)思路

1.Redis實(shí)現(xiàn)分布式鎖思路

  思路很簡單,主要用到的redis函數(shù)是setnx(),這個(gè)應(yīng)該是實(shí)現(xiàn)分布式鎖最主要的函數(shù)。首先是將某一任務(wù)標(biāo)識名(這里用Lock:order作為標(biāo)識名的例子)作為鍵存到redis里,并為其設(shè)個(gè)過期時(shí)間,如果是還有Lock:order請求過來,先是通過setnx()看看是否能將Lock:order插入到redis里,可以的話就返回true,不可以就返回false。當(dāng)然,在我的代碼里會比這個(gè)思路復(fù)雜一些,我會在分析代碼時(shí)進(jìn)一步說明。

2.Redis實(shí)現(xiàn)任務(wù)隊(duì)列

  這里的實(shí)現(xiàn)會用到上面的Redis分布式的鎖機(jī)制,主要是用到了Redis里的有序集合這一數(shù)據(jù)結(jié)構(gòu)。例如入隊(duì)時(shí),通過zset的add()函數(shù)進(jìn)行入隊(duì),而出對時(shí),可以用到zset的getScore()函數(shù)。另外還可以彈出頂部的幾個(gè)任務(wù)。

  以上就是實(shí)現(xiàn) 分布式鎖 和 任務(wù)隊(duì)列 的簡單思路,如果你看完有點(diǎn)模棱兩可,那請看接下來的代碼實(shí)現(xiàn)。

三、代碼分析

(一)先來分析Redis分布式鎖的代碼實(shí)現(xiàn)  

(1)為避免特殊原因?qū)е骆i無法釋放,在加鎖成功后,鎖會被賦予一個(gè)生存時(shí)間(通過lock方法的參數(shù)設(shè)置或者使用默認(rèn)值),超出生存時(shí)間鎖會被自動釋放鎖的生存時(shí)間默認(rèn)比較短(秒級),因此,若需要長時(shí)間加鎖,可以通過expire方法延長鎖的生存時(shí)間為適當(dāng)時(shí)間,比如在循環(huán)內(nèi)。

(2)系統(tǒng)級的鎖當(dāng)進(jìn)程無論何種原因時(shí)出現(xiàn)crash時(shí),操作系統(tǒng)會自己回收鎖,所以不會出現(xiàn)資源丟失,但分布式鎖不用,若一次性設(shè)置很長時(shí)間,一旦由于各種原因出現(xiàn)進(jìn)程crash 或者其他異常導(dǎo)致unlock未被調(diào)用時(shí),則該鎖在剩下的時(shí)間就會變成垃圾鎖,導(dǎo)致其他進(jìn)程或者進(jìn)程重啟后無法進(jìn)入加鎖區(qū)域。

先看加鎖的實(shí)現(xiàn)代碼:這里需要主要兩個(gè)參數(shù),一個(gè)是$timeout,這個(gè)是循環(huán)獲取鎖的等待時(shí)間,在這個(gè)時(shí)間內(nèi)會一直嘗試獲取鎖知道超時(shí),如果為0,則表示獲取鎖失敗后直接返回而不再等待;另一個(gè)重要參數(shù)的$expire,這個(gè)參數(shù)指當(dāng)前鎖的最大生存時(shí)間,以秒為單位的,它必須大于0,如果超過生存時(shí)間鎖仍未被釋放,則系統(tǒng)會自動強(qiáng)制釋放。這個(gè)參數(shù)的最要作用請看上面的(1)里的解釋。

  這里先取得當(dāng)前時(shí)間,然后再獲取到鎖失敗時(shí)的等待超時(shí)的時(shí)刻(是個(gè)時(shí)間戳),再獲取到鎖的最大生存時(shí)刻是多少。這里redis的key用這種格式:"Lock:鎖的標(biāo)識名",這里就開始進(jìn)入循環(huán)了,先是插入數(shù)據(jù)到redis里,使用setnx()函數(shù),這函數(shù)的意思是,如果該鍵不存在則插入數(shù)據(jù),將最大生存時(shí)刻作為值存儲,假如插入成功,則對該鍵進(jìn)行失效時(shí)間的設(shè)置,并將該鍵放在$lockedName數(shù)組里,返回true,也就是上鎖成功;如果該鍵存在,則不會插入操作了,這里有一步嚴(yán)謹(jǐn)?shù)牟僮鳎蔷褪侨〉卯?dāng)前鍵的剩余時(shí)間,假如這個(gè)時(shí)間小于0,表示key上沒有設(shè)置生存時(shí)間(key是不會不存在的,因?yàn)榍懊鎠etnx會自動創(chuàng)建)如果出現(xiàn)這種狀況,那就是進(jìn)程的某個(gè)實(shí)例setnx成功后 crash 導(dǎo)致緊跟著的expire沒有被調(diào)用,這時(shí)可以直接設(shè)置expire并把鎖納為己用。如果沒設(shè)置鎖失敗的等待時(shí)間 或者 已超過最大等待時(shí)間了,那就退出循環(huán),反之則 隔 $waitIntervalUs 后繼續(xù) 請求。  這就是加鎖的整一個(gè)代碼分析。

/**   * 加鎖   * @param [type] $name      鎖的標(biāo)識名   * @param integer $timeout    循環(huán)獲取鎖的等待超時(shí)時(shí)間,在此時(shí)間內(nèi)會一直嘗試獲取鎖直到超時(shí),為0表示失敗后直接返回不等待   * @param integer $expire     當(dāng)前鎖的最大生存時(shí)間(秒),必須大于0,如果超過生存時(shí)間鎖仍未被釋放,則系統(tǒng)會自動強(qiáng)制釋放   * @param integer $waitIntervalUs 獲取鎖失敗后掛起再試的時(shí)間間隔(微秒)   * @return [type]         [description]   */  public function lock($name, $timeout = 0, $expire = 15, $waitIntervalUs = 100000) {    if ($name == null) return false;    //取得當(dāng)前時(shí)間    $now = time();    //獲取鎖失敗時(shí)的等待超時(shí)時(shí)刻    $timeoutAt = $now + $timeout;    //鎖的最大生存時(shí)刻    $expireAt = $now + $expire;    $redisKey = "Lock:{$name}";    while (true) {      //將rediskey的最大生存時(shí)刻存到redis里,過了這個(gè)時(shí)刻該鎖會被自動釋放      $result = $this->redisString->setnx($redisKey, $expireAt);      if ($result != false) {        //設(shè)置key的失效時(shí)間        $this->redisString->expire($redisKey, $expireAt);        //將鎖標(biāo)志放到lockedNames數(shù)組里        $this->lockedNames[$name] = $expireAt;        return true;      }      //以秒為單位,返回給定key的剩余生存時(shí)間      $ttl = $this->redisString->ttl($redisKey);      //ttl小于0 表示key上沒有設(shè)置生存時(shí)間(key是不會不存在的,因?yàn)榍懊鎠etnx會自動創(chuàng)建)      //如果出現(xiàn)這種狀況,那就是進(jìn)程的某個(gè)實(shí)例setnx成功后 crash 導(dǎo)致緊跟著的expire沒有被調(diào)用      //這時(shí)可以直接設(shè)置expire并把鎖納為己用      if ($ttl < 0) {        $this->redisString->set($redisKey, $expireAt);        $this->lockedNames[$name] = $expireAt;        return true;      }      /*****循環(huán)請求鎖部分*****/      //如果沒設(shè)置鎖失敗的等待時(shí)間 或者 已超過最大等待時(shí)間了,那就退出      if ($timeout <= 0 || $timeoutAt < microtime(true)) break;      //隔 $waitIntervalUs 后繼續(xù) 請求      usleep($waitIntervalUs);    }    return false;  }

  接著看解鎖的代碼分析:解鎖就簡單多了,傳入?yún)?shù)就是鎖標(biāo)識,先是判斷是否存在該鎖,存在的話,就從redis里面通過deleteKey()函數(shù)刪除掉鎖標(biāo)識即可。

/**   * 解鎖   * @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;  }    在貼上刪除掉所有鎖的方法,其實(shí)都一個(gè)樣,多了個(gè)循環(huán)遍歷而已。/**   * 釋放當(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;  }

  以上就是用Redis實(shí)現(xiàn)分布式鎖的整一套思路和代碼實(shí)現(xiàn)的總結(jié)和分享,這里我附上正一個(gè)實(shí)現(xiàn)類的代碼,代碼里我基本上對每一行進(jìn)行了注釋,方便大家快速看懂并且能模擬應(yīng)用。想要深入了解的請看整個(gè)類的代碼:

/** *在redis上實(shí)現(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)獲取鎖的等待超時(shí)時(shí)間,在此時(shí)間內(nèi)會一直嘗試獲取鎖直到超時(shí),為0表示失敗后直接返回不等待   * @param integer $expire     當(dāng)前鎖的最大生存時(shí)間(秒),必須大于0,如果超過生存時(shí)間鎖仍未被釋放,則系統(tǒng)會自動強(qiáng)制釋放   * @param integer $waitIntervalUs 獲取鎖失敗后掛起再試的時(shí)間間隔(微秒)   * @return [type]         [description]   */  public function lock($name, $timeout = 0, $expire = 15, $waitIntervalUs = 100000) {    if ($name == null) return false;    //取得當(dāng)前時(shí)間    $now = time();    //獲取鎖失敗時(shí)的等待超時(shí)時(shí)刻    $timeoutAt = $now + $timeout;    //鎖的最大生存時(shí)刻    $expireAt = $now + $expire;    $redisKey = "Lock:{$name}";    while (true) {      //將rediskey的最大生存時(shí)刻存到redis里,過了這個(gè)時(shí)刻該鎖會被自動釋放      $result = $this->redisString->setnx($redisKey, $expireAt);      if ($result != false) {        //設(shè)置key的失效時(shí)間        $this->redisString->expire($redisKey, $expireAt);        //將鎖標(biāo)志放到lockedNames數(shù)組里        $this->lockedNames[$name] = $expireAt;        return true;      }      //以秒為單位,返回給定key的剩余生存時(shí)間      $ttl = $this->redisString->ttl($redisKey);      //ttl小于0 表示key上沒有設(shè)置生存時(shí)間(key是不會不存在的,因?yàn)榍懊鎠etnx會自動創(chuàng)建)      //如果出現(xiàn)這種狀況,那就是進(jìn)程的某個(gè)實(shí)例setnx成功后 crash 導(dǎo)致緊跟著的expire沒有被調(diào)用      //這時(shí)可以直接設(shè)置expire并把鎖納為己用      if ($ttl < 0) {        $this->redisString->set($redisKey, $expireAt);        $this->lockedNames[$name] = $expireAt;        return true;      }      /*****循環(huán)請求鎖部分*****/      //如果沒設(shè)置鎖失敗的等待時(shí)間 或者 已超過最大等待時(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)前所增加指定生存時(shí)間,必須大于0   * @param [type] $name [description]   * @return [type]    [description]   */  public function expire($name, $expire) {    //先判斷是否存在該鎖    if ($this->isLocking($name)) {      //所指定的生存時(shí)間必須大于0      $expire = max($expire, 1);      //增加鎖生存時(shí)間      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返回該鎖的生存時(shí)間      return (string)$this->lockedNames[$name] = (string)$this->redisString->get("Lock:$name");    }    return false;  }}

(二)用Redis實(shí)現(xiàn)任務(wù)隊(duì)列的代碼分析

(1)任務(wù)隊(duì)列,用于將業(yè)務(wù)邏輯中可以異步處理的操作放入隊(duì)列中,在其他線程中處理后出隊(duì)

(2)隊(duì)列中使用了分布式鎖和其他邏輯,保證入隊(duì)和出隊(duì)的一致性

(3)這個(gè)隊(duì)列和普通隊(duì)列不一樣,入隊(duì)時(shí)的id是用來區(qū)分重復(fù)入隊(duì)的,隊(duì)列里面只會有一條記錄,同一個(gè)id后入的覆蓋前入的,而不是追加, 如果需求要求重復(fù)入隊(duì)當(dāng)做不用的任務(wù),請使用不同的id區(qū)分

  先看入隊(duì)的代碼分析:首先當(dāng)然是對參數(shù)的合法性檢測,接著就用到上面加鎖機(jī)制的內(nèi)容了,就是開始加鎖,入隊(duì)時(shí)我這里選擇當(dāng)前時(shí)間戳作為score,接著就是入隊(duì)了,使用的是zset數(shù)據(jù)結(jié)構(gòu)的add()方法,入隊(duì)完成后,就對該任務(wù)解鎖,即完成了一個(gè)入隊(duì)的操作。

/**   * 入隊(duì)一個(gè) Task   * @param [type] $name     隊(duì)列名稱   * @param [type] $id      任務(wù)id(或者其數(shù)組)   * @param integer $timeout    入隊(duì)超時(shí)時(shí)間(秒)   * @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;    }        //入隊(duì)時(shí)以當(dāng)前時(shí)間戳作為 score    $score = microtime(true) + $afterInterval;    //入隊(duì)    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;  }

  接著來看一下出隊(duì)的代碼分析:出隊(duì)一個(gè)Task,需要指定它的$id 和 $score,如果$score與隊(duì)列中的匹配則出隊(duì),否則認(rèn)為該Task已被重新入隊(duì)過,當(dāng)前操作按失敗處理。首先和對參數(shù)進(jìn)行合法性檢測,接著又用到加鎖的功能了,然后及時(shí)出隊(duì)了,先使用getScore()從Redis里獲取到該id的score,然后將傳入的$score和Redis里存儲的score進(jìn)行對比,如果兩者相等就進(jìn)行出隊(duì)操作,也就是使用zset里的delete()方法刪掉該任務(wù)id,最后當(dāng)前就是解鎖了。這就是出隊(duì)的代碼分析。

/**   * 出隊(duì)一個(gè)Task,需要指定$id 和 $score   * 如果$score 與隊(duì)列中的匹配則出隊(duì),否則認(rèn)為該Task已被重新入隊(duì)過,當(dāng)前操作按失敗處理   *    * @param [type] $name  隊(duì)列名稱    * @param [type] $id   任務(wù)標(biāo)識   * @param [type] $score  任務(wù)對應(yīng)score,從隊(duì)列中獲取任務(wù)時(shí)會返回一個(gè)score,只有$score和隊(duì)列中的值匹配時(shí)Task才會被出隊(duì)   * @param integer $timeout 超時(shí)時(shí)間(秒)   * @return [type]      Task是否成功,返回false可能是redis操作失敗,也有可能是$score與隊(duì)列中的值不匹配(這表示該Task自從獲取到本地之后被其他線程入隊(duì)過)   */  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;    }        //出隊(duì)    //先取出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;  }

  學(xué)過數(shù)據(jù)結(jié)構(gòu)這門課的朋友都應(yīng)該知道,隊(duì)列操作還有彈出頂部某個(gè)值的方法等等,這里處理入隊(duì)出隊(duì)操作,我還實(shí)現(xiàn)了 獲取隊(duì)列頂部若干個(gè)Task 并將其出隊(duì)的方法,想了解的朋友可以看這段代碼,假如看不太明白就留言,這里我不再對其進(jìn)行分析了。

/**   * 獲取隊(duì)列頂部若干個(gè)Task 并將其出隊(duì)   * @param [type] $name  隊(duì)列名稱   * @param integer $count  數(shù)量   * @param integer $timeout 超時(shí)時(shí)間   * @return [type]      返回?cái)?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")) {      Log::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;  }

  以上就是用Redis實(shí)現(xiàn)任務(wù)隊(duì)列的整一套思路和代碼實(shí)現(xiàn)的總結(jié)和分享,這里我附上正一個(gè)實(shí)現(xiàn)類的代碼,代碼里我基本上對每一行進(jìn)行了注釋,方便大家快速看懂并且能模擬應(yīng)用。想要深入了解的請看整個(gè)類的代碼:

/** * 任務(wù)隊(duì)列 *  */class RedisQueue {  private $_redis;  public function __construct($param = null) {    $this->_redis = RedisFactory::get($param);  }  /**   * 入隊(duì)一個(gè) Task   * @param [type] $name     隊(duì)列名稱   * @param [type] $id      任務(wù)id(或者其數(shù)組)   * @param integer $timeout    入隊(duì)超時(shí)時(shí)間(秒)   * @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;    }        //入隊(duì)時(shí)以當(dāng)前時(shí)間戳作為 score    $score = microtime(true) + $afterInterval;    //入隊(duì)    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;  }  /**   * 出隊(duì)一個(gè)Task,需要指定$id 和 $score   * 如果$score 與隊(duì)列中的匹配則出隊(duì),否則認(rèn)為該Task已被重新入隊(duì)過,當(dāng)前操作按失敗處理   *    * @param [type] $name  隊(duì)列名稱    * @param [type] $id   任務(wù)標(biāo)識   * @param [type] $score  任務(wù)對應(yīng)score,從隊(duì)列中獲取任務(wù)時(shí)會返回一個(gè)score,只有$score和隊(duì)列中的值匹配時(shí)Task才會被出隊(duì)   * @param integer $timeout 超時(shí)時(shí)間(秒)   * @return [type]      Task是否成功,返回false可能是redis操作失敗,也有可能是$score與隊(duì)列中的值不匹配(這表示該Task自從獲取到本地之后被其他線程入隊(duì)過)   */  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;    }        //出隊(duì)    //先取出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;  }  /**   * 獲取隊(duì)列頂部若干個(gè)Task 并將其出隊(duì)   * @param [type] $name  隊(duì)列名稱   * @param integer $count  數(shù)量   * @param integer $timeout 超時(shí)時(shí)間   * @return [type]      返回?cái)?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;  }  /**   * 獲取隊(duì)列頂部的若干個(gè)Task   * @param [type] $name 隊(duì)列名稱   * @param integer $count 數(shù)量   * @return [type]     返回?cái)?shù)組[0=>['id'=> , 'score'=> ], 1=>['id'=> , 'score'=> ], 2=>['id'=> , 'score'=> ]]   */  public function top($name, $count = 1) {    //合法性檢測    if (empty($name) || $count < 1) return [];    //取錯(cuò)若干個(gè)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];    }    //返回?cái)?shù)組     return $count == 1 ? (empty($result) ? false : $result[0]) : $result;      }}

  到此,這兩大塊功能基本講解完畢,對于任務(wù)隊(duì)列,你可以寫一個(gè)shell腳本,讓服務(wù)器定時(shí)運(yùn)行某些程序,實(shí)現(xiàn)入隊(duì)出隊(duì)等操作,這里我就不在將其與實(shí)際應(yīng)用結(jié)合起來去實(shí)現(xiàn)了,大家理解好這兩大功能的實(shí)現(xiàn)思路即可,由于代碼用的是PHP語言來寫的,如果你理解了實(shí)現(xiàn)思路,你完全可以使用java或者是.net等等其他語言去實(shí)現(xiàn)這兩個(gè)功能。這兩大功能的應(yīng)用場景十分多,特別是秒殺,另一個(gè)就是春運(yùn)搶火車票,這兩個(gè)是最鮮明的例子了。當(dāng)然還有很多地方用到,這里我不再一一列舉。

  好了,本次總結(jié)和分享到此完畢。最后我附上分布式鎖和任務(wù)隊(duì)列這兩個(gè)類:

/** *在redis上實(shí)現(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)獲取鎖的等待超時(shí)時(shí)間,在此時(shí)間內(nèi)會一直嘗試獲取鎖直到超時(shí),為0表示失敗后直接返回不等待   * @param integer $expire     當(dāng)前鎖的最大生存時(shí)間(秒),必須大于0,如果超過生存時(shí)間鎖仍未被釋放,則系統(tǒng)會自動強(qiáng)制釋放   * @param integer $waitIntervalUs 獲取鎖失敗后掛起再試的時(shí)間間隔(微秒)   * @return [type]         [description]   */  public function lock($name, $timeout = 0, $expire = 15, $waitIntervalUs = 100000) {    if ($name == null) return false;    //取得當(dāng)前時(shí)間    $now = time();    //獲取鎖失敗時(shí)的等待超時(shí)時(shí)刻    $timeoutAt = $now + $timeout;    //鎖的最大生存時(shí)刻    $expireAt = $now + $expire;    $redisKey = "Lock:{$name}";    while (true) {      //將rediskey的最大生存時(shí)刻存到redis里,過了這個(gè)時(shí)刻該鎖會被自動釋放      $result = $this->redisString->setnx($redisKey, $expireAt);      if ($result != false) {        //設(shè)置key的失效時(shí)間        $this->redisString->expire($redisKey, $expireAt);        //將鎖標(biāo)志放到lockedNames數(shù)組里        $this->lockedNames[$name] = $expireAt;        return true;      }      //以秒為單位,返回給定key的剩余生存時(shí)間      $ttl = $this->redisString->ttl($redisKey);      //ttl小于0 表示key上沒有設(shè)置生存時(shí)間(key是不會不存在的,因?yàn)榍懊鎠etnx會自動創(chuàng)建)      //如果出現(xiàn)這種狀況,那就是進(jìn)程的某個(gè)實(shí)例setnx成功后 crash 導(dǎo)致緊跟著的expire沒有被調(diào)用      //這時(shí)可以直接設(shè)置expire并把鎖納為己用      if ($ttl < 0) {        $this->redisString->set($redisKey, $expireAt);        $this->lockedNames[$name] = $expireAt;        return true;      }      /*****循環(huán)請求鎖部分*****/      //如果沒設(shè)置鎖失敗的等待時(shí)間 或者 已超過最大等待時(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)前所增加指定生存時(shí)間,必須大于0   * @param [type] $name [description]   * @return [type]    [description]   */  public function expire($name, $expire) {    //先判斷是否存在該鎖    if ($this->isLocking($name)) {      //所指定的生存時(shí)間必須大于0      $expire = max($expire, 1);      //增加鎖生存時(shí)間      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返回該鎖的生存時(shí)間      return (string)$this->lockedNames[$name] = (string)$this->redisString->get("Lock:$name");    }    return false;  }}/** * 任務(wù)隊(duì)列 */class RedisQueue {  private $_redis;  public function __construct($param = null) {    $this->_redis = RedisFactory::get($param);  }  /**   * 入隊(duì)一個(gè) Task   * @param [type] $name     隊(duì)列名稱   * @param [type] $id      任務(wù)id(或者其數(shù)組)   * @param integer $timeout    入隊(duì)超時(shí)時(shí)間(秒)   * @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;    }        //入隊(duì)時(shí)以當(dāng)前時(shí)間戳作為 score    $score = microtime(true) + $afterInterval;    //入隊(duì)    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;  }  /**   * 出隊(duì)一個(gè)Task,需要指定$id 和 $score   * 如果$score 與隊(duì)列中的匹配則出隊(duì),否則認(rèn)為該Task已被重新入隊(duì)過,當(dāng)前操作按失敗處理   *    * @param [type] $name  隊(duì)列名稱    * @param [type] $id   任務(wù)標(biāo)識   * @param [type] $score  任務(wù)對應(yīng)score,從隊(duì)列中獲取任務(wù)時(shí)會返回一個(gè)score,只有$score和隊(duì)列中的值匹配時(shí)Task才會被出隊(duì)   * @param integer $timeout 超時(shí)時(shí)間(秒)   * @return [type]      Task是否成功,返回false可能是redis操作失敗,也有可能是$score與隊(duì)列中的值不匹配(這表示該Task自從獲取到本地之后被其他線程入隊(duì)過)   */  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;    }        //出隊(duì)    //先取出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;  }  /**   * 獲取隊(duì)列頂部若干個(gè)Task 并將其出隊(duì)   * @param [type] $name  隊(duì)列名稱   * @param integer $count  數(shù)量   * @param integer $timeout 超時(shí)時(shí)間   * @return [type]      返回?cái)?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;  }  /**   * 獲取隊(duì)列頂部的若干個(gè)Task   * @param [type] $name 隊(duì)列名稱   * @param integer $count 數(shù)量   * @return [type]     返回?cái)?shù)組[0=>['id'=> , 'score'=> ], 1=>['id'=> , 'score'=> ], 2=>['id'=> , 'score'=> ]]   */  public function top($name, $count = 1) {    //合法性檢測    if (empty($name) || $count < 1) return [];    //取錯(cuò)若干個(gè)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];    }    //返回?cái)?shù)組     return $count == 1 ? (empty($result) ? false : $result[0]) : $result;      }}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。



注:相關(guān)教程知識閱讀請移步到Redis頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 免费看一级毛片欧美 | 色播亚洲 | 色淫影院 | 国产又白又嫩又紧又爽18p | 免费观看视频在线观看 | av免费在线播放网址 | 香蕉视频网站在线观看 | 日韩黄色片在线观看 | 视频一区二区中文字幕 | 毛片一级网站 | 欧美性黄| 久久成人精品视频 | 日美av在线 | 国产成人77亚洲精品www | 国产xxxxx在线观看 | 国产噜噜噜噜久久久久久久久 | 成人黄色短视频在线观看 | 国产成人高潮免费观看精品 | 一区二区三区欧美日韩 | 免费毛片在线视频 | 色淫影院| 国产精品久久久久久久av三级 | 精品国产一区二 | 国产精品欧美久久久久一区二区 | 亚洲导航深夜福利涩涩屋 | 午夜小电影 | 爱逼爱操综合网 | 蜜桃视频网站在线观看 | 国产毛片网站 | 久久成人福利 | 亚洲婷婷日日综合婷婷噜噜噜 | 55夜色66夜色国产精品视频 | 国产精品性夜天天视频 | 精品国产高清一区二区三区 | 久久综合一区 | 污污网站入口 | 99精品视频99 | 久久99精品久久久久久久久久久久 | 高清视频91| 黄色小视频在线免费看 | 亚洲一区二区三区高清 |