欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2015年11月25日 14:57:57   作者:__kelly_  
這篇文章主要介紹了基于Redis實(shí)現(xiàn)分布式鎖以及任務(wù)隊(duì)列,需要的朋友可以參考下

一、前言

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

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

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

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

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

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

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

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

三、代碼分析

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

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

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

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

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

/**
   * 加鎖
   * @param [type] $name      鎖的標(biāo)識(shí)名
   * @param integer $timeout    循環(huán)獲取鎖的等待超時(shí)時(shí)間,在此時(shí)間內(nèi)會(huì)一直嘗試獲取鎖直到超時(shí),為0表示失敗后直接返回不等待
   * @param integer $expire     當(dāng)前鎖的最大生存時(shí)間(秒),必須大于0,如果超過(guò)生存時(shí)間鎖仍未被釋放,則系統(tǒng)會(huì)自動(dò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里,過(guò)了這個(gè)時(shí)刻該鎖會(huì)被自動(dòng)釋放
      $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上沒(méi)有設(shè)置生存時(shí)間(key是不會(huì)不存在的,因?yàn)榍懊鎠etnx會(huì)自動(dòng)創(chuàng)建)
      //如果出現(xiàn)這種狀況,那就是進(jìn)程的某個(gè)實(shí)例setnx成功后 crash 導(dǎo)致緊跟著的expire沒(méi)有被調(diào)用
      //這時(shí)可以直接設(shè)置expire并把鎖納為己用
      if ($ttl < 0) {
        $this->redisString->set($redisKey, $expireAt);
        $this->lockedNames[$name] = $expireAt;
        return true;
      }

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

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

    }

    return false;
  }

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

/**
   * 解鎖
   * @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)志是用來(lái)標(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)類的代碼,代碼里我基本上對(duì)每一行進(jìn)行了注釋,方便大家快速看懂并且能模擬應(yīng)用。想要深入了解的請(qǐ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)識(shí)名
   * @param integer $timeout    循環(huán)獲取鎖的等待超時(shí)時(shí)間,在此時(shí)間內(nèi)會(huì)一直嘗試獲取鎖直到超時(shí),為0表示失敗后直接返回不等待
   * @param integer $expire     當(dāng)前鎖的最大生存時(shí)間(秒),必須大于0,如果超過(guò)生存時(shí)間鎖仍未被釋放,則系統(tǒng)會(huì)自動(dò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里,過(guò)了這個(gè)時(shí)刻該鎖會(huì)被自動(dòng)釋放
      $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上沒(méi)有設(shè)置生存時(shí)間(key是不會(huì)不存在的,因?yàn)榍懊鎠etnx會(huì)自動(dòng)創(chuàng)建)
      //如果出現(xiàn)這種狀況,那就是進(jìn)程的某個(gè)實(shí)例setnx成功后 crash 導(dǎo)致緊跟著的expire沒(méi)有被調(diào)用
      //這時(shí)可以直接設(shè)置expire并把鎖納為己用
      if ($ttl < 0) {
        $this->redisString->set($redisKey, $expireAt);
        $this->lockedNames[$name] = $expireAt;
        return true;
      }

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

      //隔 $waitIntervalUs 后繼續(xù) 請(qǐng)求
      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)志是用來(lái)標(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是用來(lái)區(qū)分重復(fù)入隊(duì)的,隊(duì)列里面只會(huì)有一條記錄,同一個(gè)id后入的覆蓋前入的,而不是追加, 如果需求要求重復(fù)入隊(duì)當(dāng)做不用的任務(wù),請(qǐng)使用不同的id區(qū)分

  先看入隊(duì)的代碼分析:首先當(dāng)然是對(duì)參數(shù)的合法性檢測(cè),接著就用到上面加鎖機(jī)制的內(nèi)容了,就是開(kāi)始加鎖,入隊(duì)時(shí)我這里選擇當(dāng)前時(shí)間戳作為score,接著就是入隊(duì)了,使用的是zset數(shù)據(jù)結(jié)構(gòu)的add()方法,入隊(duì)完成后,就對(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) {
    //合法性檢測(cè)
    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;

  }

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

/**
   * 出隊(duì)一個(gè)Task,需要指定$id 和 $score
   * 如果$score 與隊(duì)列中的匹配則出隊(duì),否則認(rèn)為該Task已被重新入隊(duì)過(guò),當(dāng)前操作按失敗處理
   * 
   * @param [type] $name  隊(duì)列名稱 
   * @param [type] $id   任務(wù)標(biāo)識(shí)
   * @param [type] $score  任務(wù)對(duì)應(yīng)score,從隊(duì)列中獲取任務(wù)時(shí)會(huì)返回一個(gè)score,只有$score和隊(duì)列中的值匹配時(shí)Task才會(huì)被出隊(duì)
   * @param integer $timeout 超時(shí)時(shí)間(秒)
   * @return [type]      Task是否成功,返回false可能是redis操作失敗,也有可能是$score與隊(duì)列中的值不匹配(這表示該Task自從獲取到本地之后被其他線程入隊(duì)過(guò))
   */
  public function dequeue($name, $id, $score, $timeout = 10) {
    //合法性檢測(cè)
    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)來(lái)的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é)過(guò)數(shù)據(jù)結(jié)構(gòu)這門(mén)課的朋友都應(yīng)該知道,隊(duì)列操作還有彈出頂部某個(gè)值的方法等等,這里處理入隊(duì)出隊(duì)操作,我還實(shí)現(xiàn)了 獲取隊(duì)列頂部若干個(gè)Task 并將其出隊(duì)的方法,想了解的朋友可以看這段代碼,假如看不太明白就留言,這里我不再對(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) {
    //合法性檢測(cè)
    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對(duì)應(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)類的代碼,代碼里我基本上對(duì)每一行進(jìn)行了注釋,方便大家快速看懂并且能模擬應(yīng)用。想要深入了解的請(qǐ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) {
    //合法性檢測(cè)
    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ì)過(guò),當(dāng)前操作按失敗處理
   * 
   * @param [type] $name  隊(duì)列名稱 
   * @param [type] $id   任務(wù)標(biāo)識(shí)
   * @param [type] $score  任務(wù)對(duì)應(yīng)score,從隊(duì)列中獲取任務(wù)時(shí)會(huì)返回一個(gè)score,只有$score和隊(duì)列中的值匹配時(shí)Task才會(huì)被出隊(duì)
   * @param integer $timeout 超時(shí)時(shí)間(秒)
   * @return [type]      Task是否成功,返回false可能是redis操作失敗,也有可能是$score與隊(duì)列中的值不匹配(這表示該Task自從獲取到本地之后被其他線程入隊(duì)過(guò))
   */
  public function dequeue($name, $id, $score, $timeout = 10) {
    //合法性檢測(cè)
    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)來(lái)的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) {
    //合法性檢測(cè)
    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對(duì)應(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) {
    //合法性檢測(cè)
    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;    
  }
}

  到此,這兩大塊功能基本講解完畢,對(duì)于任務(wù)隊(duì)列,你可以寫(xiě)一個(gè)shell腳本,讓服務(wù)器定時(shí)運(yùn)行某些程序,實(shí)現(xiàn)入隊(duì)出隊(duì)等操作,這里我就不在將其與實(shí)際應(yīng)用結(jié)合起來(lái)去實(shí)現(xiàn)了,大家理解好這兩大功能的實(shí)現(xiàn)思路即可,由于代碼用的是PHP語(yǔ)言來(lái)寫(xiě)的,如果你理解了實(shí)現(xiàn)思路,你完全可以使用java或者是.net等等其他語(yǔ)言去實(shí)現(xiàn)這兩個(gè)功能。這兩大功能的應(yīng)用場(chǎng)景十分多,特別是秒殺,另一個(gè)就是春運(yùn)搶火車(chē)票,這兩個(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)識(shí)名
   * @param integer $timeout    循環(huán)獲取鎖的等待超時(shí)時(shí)間,在此時(shí)間內(nèi)會(huì)一直嘗試獲取鎖直到超時(shí),為0表示失敗后直接返回不等待
   * @param integer $expire     當(dāng)前鎖的最大生存時(shí)間(秒),必須大于0,如果超過(guò)生存時(shí)間鎖仍未被釋放,則系統(tǒng)會(huì)自動(dò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里,過(guò)了這個(gè)時(shí)刻該鎖會(huì)被自動(dòng)釋放
      $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上沒(méi)有設(shè)置生存時(shí)間(key是不會(huì)不存在的,因?yàn)榍懊鎠etnx會(huì)自動(dòng)創(chuàng)建)
      //如果出現(xiàn)這種狀況,那就是進(jìn)程的某個(gè)實(shí)例setnx成功后 crash 導(dǎo)致緊跟著的expire沒(méi)有被調(diào)用
      //這時(shí)可以直接設(shè)置expire并把鎖納為己用
      if ($ttl < 0) {
        $this->redisString->set($redisKey, $expireAt);
        $this->lockedNames[$name] = $expireAt;
        return true;
      }

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

      //隔 $waitIntervalUs 后繼續(xù) 請(qǐng)求
      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)志是用來(lái)標(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) {
    //合法性檢測(cè)
    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ì)過(guò),當(dāng)前操作按失敗處理
   * 
   * @param [type] $name  隊(duì)列名稱 
   * @param [type] $id   任務(wù)標(biāo)識(shí)
   * @param [type] $score  任務(wù)對(duì)應(yīng)score,從隊(duì)列中獲取任務(wù)時(shí)會(huì)返回一個(gè)score,只有$score和隊(duì)列中的值匹配時(shí)Task才會(huì)被出隊(duì)
   * @param integer $timeout 超時(shí)時(shí)間(秒)
   * @return [type]      Task是否成功,返回false可能是redis操作失敗,也有可能是$score與隊(duì)列中的值不匹配(這表示該Task自從獲取到本地之后被其他線程入隊(duì)過(guò))
   */
  public function dequeue($name, $id, $score, $timeout = 10) {
    //合法性檢測(cè)
    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)來(lái)的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) {
    //合法性檢測(cè)
    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對(duì)應(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) {
    //合法性檢測(cè)
    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;    
  }
}

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

相關(guān)文章

  • 解決Redis啟動(dòng)警告問(wèn)題

    解決Redis啟動(dòng)警告問(wèn)題

    這篇文章介紹了解決Redis啟動(dòng)警告問(wèn)題的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-02-02
  • Linux安裝Redis、后臺(tái)運(yùn)行、系統(tǒng)自啟動(dòng)的設(shè)置方法

    Linux安裝Redis、后臺(tái)運(yùn)行、系統(tǒng)自啟動(dòng)的設(shè)置方法

    Redis是用C語(yǔ)言編寫(xiě)的開(kāi)源免費(fèi)的高性能的分布式內(nèi)存數(shù)據(jù)庫(kù),基于內(nèi)存運(yùn)行并支持持久化的NoSQL數(shù)據(jù)庫(kù)。這篇文章主要介紹了Linux安裝Redis、后臺(tái)運(yùn)行、系統(tǒng)自啟動(dòng),需要的朋友可以參考下
    2020-01-01
  • 如何利用 Redis 實(shí)現(xiàn)接口頻次限制

    如何利用 Redis 實(shí)現(xiàn)接口頻次限制

    這篇文章主要介紹了如何利用 Redis 實(shí)現(xiàn)接口頻次限制,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-02-02
  • 淺談Redis緩存擊穿、緩存穿透、緩存雪崩的解決方案

    淺談Redis緩存擊穿、緩存穿透、緩存雪崩的解決方案

    這篇文章主要介紹了淺談Redis緩存擊穿、緩存穿透、緩存雪崩的解決方案,緩存是分布式系統(tǒng)中的重要組件,主要解決在高并發(fā)、大數(shù)據(jù)場(chǎng)景下,熱點(diǎn)數(shù)據(jù)訪問(wèn)的性能問(wèn)題,需要的朋友可以參考下
    2023-03-03
  • redis的bigkey掃描腳本深入介紹

    redis的bigkey掃描腳本深入介紹

    這篇文章主要給大家介紹了關(guān)于redis的bigkey掃描腳本的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2018-07-07
  • 如何保證Redis與數(shù)據(jù)庫(kù)的數(shù)據(jù)一致性

    如何保證Redis與數(shù)據(jù)庫(kù)的數(shù)據(jù)一致性

    這篇文章主要介紹了如何保證Redis與數(shù)據(jù)庫(kù)的數(shù)據(jù)一致性,文中舉了兩個(gè)場(chǎng)景例子介紹的非常詳細(xì),需要的朋友可以參考下
    2023-05-05
  • window下創(chuàng)建redis出現(xiàn)問(wèn)題小結(jié)

    window下創(chuàng)建redis出現(xiàn)問(wèn)題小結(jié)

    這篇文章主要介紹了window下創(chuàng)建redis出現(xiàn)問(wèn)題總結(jié),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-10-10
  • Redis中Redisson布隆過(guò)濾器的學(xué)習(xí)

    Redis中Redisson布隆過(guò)濾器的學(xué)習(xí)

    布隆過(guò)濾器是一個(gè)非常長(zhǎng)的二進(jìn)制向量和一系列隨機(jī)哈希函數(shù)的組合,可用于檢索一個(gè)元素是否存在,本文就詳細(xì)的介紹一下Redisson布隆過(guò)濾器,具有一定的參考價(jià)值,感興趣的可以了解一下
    2022-05-05
  • redis?sentinel監(jiān)控高可用集群實(shí)現(xiàn)的配置步驟

    redis?sentinel監(jiān)控高可用集群實(shí)現(xiàn)的配置步驟

    這篇文章主要介紹了redis?sentinel監(jiān)控高可用集群實(shí)現(xiàn)的配置步驟,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪
    2022-04-04
  • 如何使用redis中的zset實(shí)現(xiàn)滑動(dòng)窗口限流

    如何使用redis中的zset實(shí)現(xiàn)滑動(dòng)窗口限流

    滑動(dòng)窗口限流是一種常見(jiàn)的流量控制方法,它限制了在一定時(shí)間窗口內(nèi)的請(qǐng)求數(shù)量,下面是使用Redis ZSet實(shí)現(xiàn)滑動(dòng)窗口限流的一個(gè)簡(jiǎn)單示例,需要的朋友可以參考下
    2023-09-09

最新評(píng)論