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

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

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

2020-10-28 21:40:00
字體:
供稿:網(wǎng)友

一、前言

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

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

二、實現(xiàn)思路

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

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

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

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

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

三、代碼分析

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

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

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

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

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

/**   * 加鎖   * @param [type] $name      鎖的標識名   * @param integer $timeout    循環(huán)獲取鎖的等待超時時間,在此時間內(nèi)會一直嘗試獲取鎖直到超時,為0表示失敗后直接返回不等待   * @param integer $expire     當前鎖的最大生存時間(秒),必須大于0,如果超過生存時間鎖仍未被釋放,則系統(tǒng)會自動強制釋放   * @param integer $waitIntervalUs 獲取鎖失敗后掛起再試的時間間隔(微秒)   * @return [type]         [description]   */  public function lock($name, $timeout = 0, $expire = 15, $waitIntervalUs = 100000) {    if ($name == null) return false;    //取得當前時間    $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);        //將鎖標志放到lockedNames數(shù)組里        $this->lockedNames[$name] = $expireAt;        return true;      }      //以秒為單位,返回給定key的剩余生存時間      $ttl = $this->redisString->ttl($redisKey);      //ttl小于0 表示key上沒有設(shè)置生存時間(key是不會不存在的,因為前面setnx會自動創(chuàng)建)      //如果出現(xià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;  }

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

/**   * 解鎖   * @param [type] $name [description]   * @return [type]    [description]   */  public function unlock($name) {    //先判斷是否存在此鎖    if ($this->isLocking($name)) {      //刪除鎖      if ($this->redisString->deleteKey("Lock:$name")) {        //清掉lockedNames里的鎖標志        unset($this->lockedNames[$name]);        return true;      }    }    return false;  }    在貼上刪除掉所有鎖的方法,其實都一個樣,多了個循環(huán)遍歷而已。/**   * 釋放當前所有獲得的鎖   * @return [type] [description]   */  public function unlockAll() {    //此標志是用來標志是否釋放所有鎖成功    $allSuccess = true;    foreach ($this->lockedNames as $name => $expireAt) {      if (false === $this->unlock($name)) {        $allSuccess = false;        }    }    return $allSuccess;  }

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

/** *在redis上實現(xiàn)分布式鎖 */class RedisLock {  private $redisString;  private $lockedNames = [];  public function __construct($param = NULL) {    $this->redisString = RedisFactory::get($param)->string;  }  /**   * 加鎖   * @param [type] $name      鎖的標識名   * @param integer $timeout    循環(huán)獲取鎖的等待超時時間,在此時間內(nèi)會一直嘗試獲取鎖直到超時,為0表示失敗后直接返回不等待   * @param integer $expire     當前鎖的最大生存時間(秒),必須大于0,如果超過生存時間鎖仍未被釋放,則系統(tǒng)會自動強制釋放   * @param integer $waitIntervalUs 獲取鎖失敗后掛起再試的時間間隔(微秒)   * @return [type]         [description]   */  public function lock($name, $timeout = 0, $expire = 15, $waitIntervalUs = 100000) {    if ($name == null) return false;    //取得當前時間    $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);        //將鎖標志放到lockedNames數(shù)組里        $this->lockedNames[$name] = $expireAt;        return true;      }      //以秒為單位,返回給定key的剩余生存時間      $ttl = $this->redisString->ttl($redisKey);      //ttl小于0 表示key上沒有設(shè)置生存時間(key是不會不存在的,因為前面setnx會自動創(chuàng)建)      //如果出現(xià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里的鎖標志        unset($this->lockedNames[$name]);        return true;      }    }    return false;  }  /**   * 釋放當前所有獲得的鎖   * @return [type] [description]   */  public function unlockAll() {    //此標志是用來標志是否釋放所有鎖成功    $allSuccess = true;    foreach ($this->lockedNames as $name => $expireAt) {      if (false === $this->unlock($name)) {        $allSuccess = false;        }    }    return $allSuccess;  }  /**   * 給當前所增加指定生存時間,必須大于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;  }  /**   * 判斷當前是否擁有指定名字的所   * @param [type] $name [description]   * @return boolean    [description]   */  public function isLocking($name) {    //先看lonkedName[$name]是否存在該鎖標志名    if (isset($this->lockedNames[$name])) {      //從redis返回該鎖的生存時間      return (string)$this->lockedNames[$name] = (string)$this->redisString->get("Lock:$name");    }    return false;  }}

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

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

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

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

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

/**   * 入隊一個 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;    }        //入隊時以當前時間戳作為 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與隊列中的匹配則出隊,否則認為該Task已被重新入隊過,當前操作按失敗處理。首先和對參數(shù)進行合法性檢測,接著又用到加鎖的功能了,然后及時出隊了,先使用getScore()從Redis里獲取到該id的score,然后將傳入的$score和Redis里存儲的score進行對比,如果兩者相等就進行出隊操作,也就是使用zset里的delete()方法刪掉該任務(wù)id,最后當前就是解鎖了。這就是出隊的代碼分析。

/**   * 出隊一個Task,需要指定$id 和 $score   * 如果$score 與隊列中的匹配則出隊,否則認為該Task已被重新入隊過,當前操作按失敗處理   *    * @param [type] $name  隊列名稱    * @param [type] $id   任務(wù)標識   * @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;    //先判斷傳進來的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)該知道,隊列操作還有彈出頂部某個值的方法等等,這里處理入隊出隊操作,我還實現(xiàn)了 獲取隊列頂部若干個Task 并將其出隊的方法,想了解的朋友可以看這段代碼,假如看不太明白就留言,這里我不再對其進行分析了。

/**   * 獲取隊列頂部若干個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")) {      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實現(xiàn)任務(wù)隊列的整一套思路和代碼實現(xiàn)的總結(jié)和分享,這里我附上正一個實現(xiàn)類的代碼,代碼里我基本上對每一行進行了注釋,方便大家快速看懂并且能模擬應(yīng)用。想要深入了解的請看整個類的代碼:

/** * 任務(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;    }        //入隊時以當前時間戳作為 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 與隊列中的匹配則出隊,否則認為該Task已被重新入隊過,當前操作按失敗處理   *    * @param [type] $name  隊列名稱    * @param [type] $id   任務(wù)標識   * @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;    //先判斷傳進來的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;      }}

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

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

/** *在redis上實現(xiàn)分布式鎖 */class RedisLock {  private $redisString;  private $lockedNames = [];  public function __construct($param = NULL) {    $this->redisString = RedisFactory::get($param)->string;  }  /**   * 加鎖   * @param [type] $name      鎖的標識名   * @param integer $timeout    循環(huán)獲取鎖的等待超時時間,在此時間內(nèi)會一直嘗試獲取鎖直到超時,為0表示失敗后直接返回不等待   * @param integer $expire     當前鎖的最大生存時間(秒),必須大于0,如果超過生存時間鎖仍未被釋放,則系統(tǒng)會自動強制釋放   * @param integer $waitIntervalUs 獲取鎖失敗后掛起再試的時間間隔(微秒)   * @return [type]         [description]   */  public function lock($name, $timeout = 0, $expire = 15, $waitIntervalUs = 100000) {    if ($name == null) return false;    //取得當前時間    $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);        //將鎖標志放到lockedNames數(shù)組里        $this->lockedNames[$name] = $expireAt;        return true;      }      //以秒為單位,返回給定key的剩余生存時間      $ttl = $this->redisString->ttl($redisKey);      //ttl小于0 表示key上沒有設(shè)置生存時間(key是不會不存在的,因為前面setnx會自動創(chuàng)建)      //如果出現(xià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里的鎖標志        unset($this->lockedNames[$name]);        return true;      }    }    return false;  }  /**   * 釋放當前所有獲得的鎖   * @return [type] [description]   */  public function unlockAll() {    //此標志是用來標志是否釋放所有鎖成功    $allSuccess = true;    foreach ($this->lockedNames as $name => $expireAt) {      if (false === $this->unlock($name)) {        $allSuccess = false;        }    }    return $allSuccess;  }  /**   * 給當前所增加指定生存時間,必須大于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;  }  /**   * 判斷當前是否擁有指定名字的所   * @param [type] $name [description]   * @return boolean    [description]   */  public function isLocking($name) {    //先看lonkedName[$name]是否存在該鎖標志名    if (isset($this->lockedNames[$name])) {      //從redis返回該鎖的生存時間      return (string)$this->lockedNames[$name] = (string)$this->redisString->get("Lock:$name");    }    return false;  }}/** * 任務(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;    }        //入隊時以當前時間戳作為 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 與隊列中的匹配則出隊,否則認為該Task已被重新入隊過,當前操作按失敗處理   *    * @param [type] $name  隊列名稱    * @param [type] $id   任務(wù)標識   * @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;    //先判斷傳進來的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;      }}

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

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 久久精品99国产国产精 | 久草干| 国产乱淫a∨片免费观看 | 国产电影av在线 | 99re热视频这里只精品 | 久久亚洲国产精品 | 激情97| 免费黄色在线观看网站 | 欧美一区二区三区久久精品视 | 久久精品亚洲欧美日韩精品中文字幕 | 俄罗斯16一20sex牲色另类 | 成人三级电影网 | 日本在线播放一区二区 | 国产亚洲高清视频 | av在线免费电影 | 免费网站看v片在线a | 国产精品久久久久久久久久三级 | 色视频欧美| 日本娇小videos高潮 | 国产精品一区二区在线 | 久久影库 | 久久综合久久精品 | 日本成人二区 | 亚洲一区在线国产 | 国产精品亚洲欧美 | 在线区| 激情国产视频 | 黄视频免费在线 | 一本大道av| 成人一级视频 | 激情夜色 | 九九福利视频 | 欧美成人精品一区二区三区 | 草草久久久| 一级毛片在线免费播放 | 久久久久97国产精 | aa国产视频一区二区 | 国产精品视频六区 | 爱福利视频网 | 色屁屁xxxxⅹ在线视频 | 国产成人在线观看免费 |