一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|數據庫技術|

服務器之家 - 數據庫 - Redis - 基于Redis實現分布式鎖以及任務隊列

基于Redis實現分布式鎖以及任務隊列

2019-10-27 16:35__kelly_ Redis

這篇文章主要介紹了基于Redis實現分布式鎖以及任務隊列,需要的朋友可以參考下

一、前言

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

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

二、實現思路

1.Redis實現分布式鎖思路

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

2.Redis實現任務隊列

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

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

三、代碼分析

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

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

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

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

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

  1. /** 
  2.    * 加鎖 
  3.    * @param [type] $name      鎖的標識名 
  4.    * @param integer $timeout    循環獲取鎖的等待超時時間,在此時間內會一直嘗試獲取鎖直到超時,為0表示失敗后直接返回不等待 
  5.    * @param integer $expire     當前鎖的最大生存時間(秒),必須大于0,如果超過生存時間鎖仍未被釋放,則系統會自動強制釋放 
  6.    * @param integer $waitIntervalUs 獲取鎖失敗后掛起再試的時間間隔(微秒) 
  7.    * @return [type]         [description] 
  8.    */ 
  9.   public function lock($name, $timeout = 0, $expire = 15, $waitIntervalUs = 100000) { 
  10.     if ($name == nullreturn false
  11.  
  12.     //取得當前時間 
  13.     $now = time(); 
  14.     //獲取鎖失敗時的等待超時時刻 
  15.     $timeoutAt = $now + $timeout; 
  16.     //鎖的最大生存時刻 
  17.     $expireAt = $now + $expire; 
  18.  
  19.     $redisKey = "Lock:{$name}"
  20.     while (true) { 
  21.       //將rediskey的最大生存時刻存到redis里,過了這個時刻該鎖會被自動釋放 
  22.       $result = $this->redisString->setnx($redisKey, $expireAt); 
  23.  
  24.       if ($result != false) { 
  25.         //設置key的失效時間 
  26.         $this->redisString->expire($redisKey, $expireAt); 
  27.         //將鎖標志放到lockedNames數組里 
  28.         $this->lockedNames[$name] = $expireAt; 
  29.         return true
  30.       } 
  31.  
  32.       //以秒為單位,返回給定key的剩余生存時間 
  33.       $ttl = $this->redisString->ttl($redisKey); 
  34.  
  35.       //ttl小于0 表示key上沒有設置生存時間(key是不會不存在的,因為前面setnx會自動創建) 
  36.       //如果出現這種狀況,那就是進程的某個實例setnx成功后 crash 導致緊跟著的expire沒有被調用 
  37.       //這時可以直接設置expire并把鎖納為己用 
  38.       if ($ttl < 0) { 
  39.         $this->redisString->set($redisKey, $expireAt); 
  40.         $this->lockedNames[$name] = $expireAt; 
  41.         return true
  42.       } 
  43.  
  44.       /*****循環請求鎖部分*****/ 
  45.       //如果沒設置鎖失敗的等待時間 或者 已超過最大等待時間了,那就退出 
  46.       if ($timeout <= 0 || $timeoutAt < microtime(true)) break
  47.  
  48.       //隔 $waitIntervalUs 后繼續 請求 
  49.       usleep($waitIntervalUs); 
  50.  
  51.     } 
  52.  
  53.     return false
  54.   } 

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

  1. /** 
  2.    * 解鎖 
  3.    * @param [type] $name [description] 
  4.    * @return [type]    [description] 
  5.    */ 
  6.   public function unlock($name) { 
  7.     //先判斷是否存在此鎖 
  8.     if ($this->isLocking($name)) { 
  9.       //刪除鎖 
  10.       if ($this->redisString->deleteKey("Lock:$name")) { 
  11.         //清掉lockedNames里的鎖標志 
  12.         unset($this->lockedNames[$name]); 
  13.         return true
  14.       } 
  15.     } 
  16.     return false
  17.   } 
  18.     在貼上刪除掉所有鎖的方法,其實都一個樣,多了個循環遍歷而已。 
  19. /** 
  20.    * 釋放當前所有獲得的鎖 
  21.    * @return [type] [description] 
  22.    */ 
  23.   public function unlockAll() { 
  24.     //此標志是用來標志是否釋放所有鎖成功 
  25.     $allSuccess = true
  26.     foreach ($this->lockedNames as $name => $expireAt) { 
  27.       if (false === $this->unlock($name)) { 
  28.         $allSuccess = false;  
  29.       } 
  30.     } 
  31.     return $allSuccess; 
  32.   } 

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

  1. /** 
  2.  *在redis上實現分布式鎖 
  3.  */ 
  4. class RedisLock { 
  5.   private $redisString; 
  6.   private $lockedNames = []; 
  7.  
  8.   public function __construct($param = NULL) { 
  9.     $this->redisString = RedisFactory::get($param)->string; 
  10.   } 
  11.  
  12.   /** 
  13.    * 加鎖 
  14.    * @param [type] $name      鎖的標識名 
  15.    * @param integer $timeout    循環獲取鎖的等待超時時間,在此時間內會一直嘗試獲取鎖直到超時,為0表示失敗后直接返回不等待 
  16.    * @param integer $expire     當前鎖的最大生存時間(秒),必須大于0,如果超過生存時間鎖仍未被釋放,則系統會自動強制釋放 
  17.    * @param integer $waitIntervalUs 獲取鎖失敗后掛起再試的時間間隔(微秒) 
  18.    * @return [type]         [description] 
  19.    */ 
  20.   public function lock($name, $timeout = 0, $expire = 15, $waitIntervalUs = 100000) { 
  21.     if ($name == nullreturn false
  22.  
  23.     //取得當前時間 
  24.     $now = time(); 
  25.     //獲取鎖失敗時的等待超時時刻 
  26.     $timeoutAt = $now + $timeout; 
  27.     //鎖的最大生存時刻 
  28.     $expireAt = $now + $expire; 
  29.  
  30.     $redisKey = "Lock:{$name}"
  31.     while (true) { 
  32.       //將rediskey的最大生存時刻存到redis里,過了這個時刻該鎖會被自動釋放 
  33.       $result = $this->redisString->setnx($redisKey, $expireAt); 
  34.  
  35.       if ($result != false) { 
  36.         //設置key的失效時間 
  37.         $this->redisString->expire($redisKey, $expireAt); 
  38.         //將鎖標志放到lockedNames數組里 
  39.         $this->lockedNames[$name] = $expireAt; 
  40.         return true
  41.       } 
  42.  
  43.       //以秒為單位,返回給定key的剩余生存時間 
  44.       $ttl = $this->redisString->ttl($redisKey); 
  45.  
  46.       //ttl小于0 表示key上沒有設置生存時間(key是不會不存在的,因為前面setnx會自動創建) 
  47.       //如果出現這種狀況,那就是進程的某個實例setnx成功后 crash 導致緊跟著的expire沒有被調用 
  48.       //這時可以直接設置expire并把鎖納為己用 
  49.       if ($ttl < 0) { 
  50.         $this->redisString->set($redisKey, $expireAt); 
  51.         $this->lockedNames[$name] = $expireAt; 
  52.         return true
  53.       } 
  54.  
  55.       /*****循環請求鎖部分*****/ 
  56.       //如果沒設置鎖失敗的等待時間 或者 已超過最大等待時間了,那就退出 
  57.       if ($timeout <= 0 || $timeoutAt < microtime(true)) break
  58.  
  59.       //隔 $waitIntervalUs 后繼續 請求 
  60.       usleep($waitIntervalUs); 
  61.  
  62.     } 
  63.  
  64.     return false
  65.   } 
  66.  
  67.   /** 
  68.    * 解鎖 
  69.    * @param [type] $name [description] 
  70.    * @return [type]    [description] 
  71.    */ 
  72.   public function unlock($name) { 
  73.     //先判斷是否存在此鎖 
  74.     if ($this->isLocking($name)) { 
  75.       //刪除鎖 
  76.       if ($this->redisString->deleteKey("Lock:$name")) { 
  77.         //清掉lockedNames里的鎖標志 
  78.         unset($this->lockedNames[$name]); 
  79.         return true
  80.       } 
  81.     } 
  82.     return false
  83.   } 
  84.  
  85.   /** 
  86.    * 釋放當前所有獲得的鎖 
  87.    * @return [type] [description] 
  88.    */ 
  89.   public function unlockAll() { 
  90.     //此標志是用來標志是否釋放所有鎖成功 
  91.     $allSuccess = true
  92.     foreach ($this->lockedNames as $name => $expireAt) { 
  93.       if (false === $this->unlock($name)) { 
  94.         $allSuccess = false;  
  95.       } 
  96.     } 
  97.     return $allSuccess; 
  98.   } 
  99.  
  100.   /** 
  101.    * 給當前所增加指定生存時間,必須大于0 
  102.    * @param [type] $name [description] 
  103.    * @return [type]    [description] 
  104.    */ 
  105.   public function expire($name, $expire) { 
  106.     //先判斷是否存在該鎖 
  107.     if ($this->isLocking($name)) { 
  108.       //所指定的生存時間必須大于0 
  109.       $expire = max($expire, 1); 
  110.       //增加鎖生存時間 
  111.       if ($this->redisString->expire("Lock:$name", $expire)) { 
  112.         return true
  113.       } 
  114.     } 
  115.     return false
  116.   } 
  117.  
  118.   /** 
  119.    * 判斷當前是否擁有指定名字的所 
  120.    * @param [type] $name [description] 
  121.    * @return boolean    [description] 
  122.    */ 
  123.   public function isLocking($name) { 
  124.     //先看lonkedName[$name]是否存在該鎖標志名 
  125.     if (isset($this->lockedNames[$name])) { 
  126.       //從redis返回該鎖的生存時間 
  127.       return (string)$this->lockedNames[$name] = (string)$this->redisString->get("Lock:$name"); 
  128.     } 
  129.  
  130.     return false
  131.   } 
  132.  

(二)用Redis實現任務隊列的代碼分析

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

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

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

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

  1. /** 
  2.    * 入隊一個 Task 
  3.    * @param [type] $name     隊列名稱 
  4.    * @param [type] $id      任務id(或者其數組) 
  5.    * @param integer $timeout    入隊超時時間(秒) 
  6.    * @param integer $afterInterval [description] 
  7.    * @return [type]         [description] 
  8.    */ 
  9.   public function enqueue($name, $id, $timeout = 10, $afterInterval = 0) { 
  10.     //合法性檢測 
  11.     if (empty($name) || empty($id) || $timeout <= 0) return false
  12.  
  13.     //加鎖 
  14.     if (!$this->_redis->lock->lock("Queue:{$name}", $timeout)) { 
  15.       Logger::get('queue')->error("enqueue faild becouse of lock failure: name = $name, id = $id"); 
  16.       return false
  17.     } 
  18.      
  19.     //入隊時以當前時間戳作為 score 
  20.     $score = microtime(true) + $afterInterval; 
  21.     //入隊 
  22.     foreach ((array)$id as $item) { 
  23.       //先判斷下是否已經存在該id了 
  24.       if (false === $this->_redis->zset->getScore("Queue:$name", $item)) { 
  25.         $this->_redis->zset->add("Queue:$name", $score, $item); 
  26.       } 
  27.     } 
  28.      
  29.     //解鎖 
  30.     $this->_redis->lock->unlock("Queue:$name"); 
  31.  
  32.     return true
  33.  
  34.   } 

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

  1. /** 
  2.    * 出隊一個Task,需要指定$id 和 $score 
  3.    * 如果$score 與隊列中的匹配則出隊,否則認為該Task已被重新入隊過,當前操作按失敗處理 
  4.    * 
  5.    * @param [type] $name  隊列名稱 
  6.    * @param [type] $id   任務標識 
  7.    * @param [type] $score  任務對應score,從隊列中獲取任務時會返回一個score,只有$score和隊列中的值匹配時Task才會被出隊 
  8.    * @param integer $timeout 超時時間(秒) 
  9.    * @return [type]      Task是否成功,返回false可能是redis操作失敗,也有可能是$score與隊列中的值不匹配(這表示該Task自從獲取到本地之后被其他線程入隊過) 
  10.    */ 
  11.   public function dequeue($name, $id, $score, $timeout = 10) { 
  12.     //合法性檢測 
  13.     if (empty($name) || empty($id) || empty($score)) return false
  14.      
  15.     //加鎖 
  16.     if (!$this->_redis->lock->lock("Queue:$name", $timeout)) { 
  17.       Logger:get('queue')->error("dequeue faild becouse of lock lailure:name=$name, id = $id"); 
  18.       return false
  19.     } 
  20.      
  21.     //出隊 
  22.     //先取出redis的score 
  23.     $serverScore = $this->_redis->zset->getScore("Queue:$name", $id); 
  24.     $result = false
  25.     //先判斷傳進來的score和redis的score是否是一樣 
  26.     if ($serverScore == $score) { 
  27.       //刪掉該$id 
  28.       $result = (float)$this->_redis->zset->delete("Queue:$name", $id); 
  29.       if ($result == false) { 
  30.         Logger::get('queue')->error("dequeue faild because of redis delete failure: name =$name, id = $id"); 
  31.       } 
  32.     } 
  33.     //解鎖 
  34.     $this->_redis->lock->unlock("Queue:$name"); 
  35.  
  36.     return $result; 
  37.   } 

  學過數據結構這門課的朋友都應該知道,隊列操作還有彈出頂部某個值的方法等等,這里處理入隊出隊操作,我還實現了 獲取隊列頂部若干個Task 并將其出隊的方法,想了解的朋友可以看這段代碼,假如看不太明白就留言,這里我不再對其進行分析了。

  1. /** 
  2.    * 獲取隊列頂部若干個Task 并將其出隊 
  3.    * @param [type] $name  隊列名稱 
  4.    * @param integer $count  數量 
  5.    * @param integer $timeout 超時時間 
  6.    * @return [type]      返回數組[0=>['id'=> , 'score'=> ], 1=>['id'=> , 'score'=> ], 2=>['id'=> , 'score'=> ]] 
  7.    */ 
  8.   public function pop($name, $count = 1, $timeout = 10) { 
  9.     //合法性檢測 
  10.     if (empty($name) || $count <= 0) return []; 
  11.      
  12.     //加鎖 
  13.     if (!$this->_redis->lock->lock("Queue:$name")) { 
  14.       Log::get('queue')->error("pop faild because of pop failure: name = $name, count = $count"); 
  15.       return false
  16.     } 
  17.      
  18.     //取出若干的Task 
  19.     $result = []; 
  20.     $array = $this->_redis->zset->getByScore("Queue:$name"false, microtime(true), truefalse, [0, $count]); 
  21.  
  22.     //將其放在$result數組里 并 刪除掉redis對應的id 
  23.     foreach ($array as $id => $score) { 
  24.       $result[] = ['id'=>$id, 'score'=>$score]; 
  25.       $this->_redis->zset->delete("Queue:$name", $id); 
  26.     } 
  27.  
  28.     //解鎖 
  29.     $this->_redis->lock->unlock("Queue:$name"); 
  30.  
  31.     return $count == 1 ? (empty($result) ? false : $result[0]) : $result; 
  32.   } 

  以上就是用Redis實現任務隊列的整一套思路和代碼實現的總結和分享,這里我附上正一個實現類的代碼,代碼里我基本上對每一行進行了注釋,方便大家快速看懂并且能模擬應用。想要深入了解的請看整個類的代碼:

  1. /** 
  2.  * 任務隊列 
  3.  * 
  4.  */ 
  5. class RedisQueue { 
  6.   private $_redis; 
  7.  
  8.   public function __construct($param = null) { 
  9.     $this->_redis = RedisFactory::get($param); 
  10.   } 
  11.  
  12.   /** 
  13.    * 入隊一個 Task 
  14.    * @param [type] $name     隊列名稱 
  15.    * @param [type] $id      任務id(或者其數組) 
  16.    * @param integer $timeout    入隊超時時間(秒) 
  17.    * @param integer $afterInterval [description] 
  18.    * @return [type]         [description] 
  19.    */ 
  20.   public function enqueue($name, $id, $timeout = 10, $afterInterval = 0) { 
  21.     //合法性檢測 
  22.     if (empty($name) || empty($id) || $timeout <= 0) return false
  23.  
  24.     //加鎖 
  25.     if (!$this->_redis->lock->lock("Queue:{$name}", $timeout)) { 
  26.       Logger::get('queue')->error("enqueue faild becouse of lock failure: name = $name, id = $id"); 
  27.       return false
  28.     } 
  29.      
  30.     //入隊時以當前時間戳作為 score 
  31.     $score = microtime(true) + $afterInterval; 
  32.     //入隊 
  33.     foreach ((array)$id as $item) { 
  34.       //先判斷下是否已經存在該id了 
  35.       if (false === $this->_redis->zset->getScore("Queue:$name", $item)) { 
  36.         $this->_redis->zset->add("Queue:$name", $score, $item); 
  37.       } 
  38.     } 
  39.      
  40.     //解鎖 
  41.     $this->_redis->lock->unlock("Queue:$name"); 
  42.  
  43.     return true
  44.  
  45.   } 
  46.  
  47.   /** 
  48.    * 出隊一個Task,需要指定$id 和 $score 
  49.    * 如果$score 與隊列中的匹配則出隊,否則認為該Task已被重新入隊過,當前操作按失敗處理 
  50.    * 
  51.    * @param [type] $name  隊列名稱 
  52.    * @param [type] $id   任務標識 
  53.    * @param [type] $score  任務對應score,從隊列中獲取任務時會返回一個score,只有$score和隊列中的值匹配時Task才會被出隊 
  54.    * @param integer $timeout 超時時間(秒) 
  55.    * @return [type]      Task是否成功,返回false可能是redis操作失敗,也有可能是$score與隊列中的值不匹配(這表示該Task自從獲取到本地之后被其他線程入隊過) 
  56.    */ 
  57.   public function dequeue($name, $id, $score, $timeout = 10) { 
  58.     //合法性檢測 
  59.     if (empty($name) || empty($id) || empty($score)) return false
  60.      
  61.     //加鎖 
  62.     if (!$this->_redis->lock->lock("Queue:$name", $timeout)) { 
  63.       Logger:get('queue')->error("dequeue faild becouse of lock lailure:name=$name, id = $id"); 
  64.       return false
  65.     } 
  66.      
  67.     //出隊 
  68.     //先取出redis的score 
  69.     $serverScore = $this->_redis->zset->getScore("Queue:$name", $id); 
  70.     $result = false
  71.     //先判斷傳進來的score和redis的score是否是一樣 
  72.     if ($serverScore == $score) { 
  73.       //刪掉該$id 
  74.       $result = (float)$this->_redis->zset->delete("Queue:$name", $id); 
  75.       if ($result == false) { 
  76.         Logger::get('queue')->error("dequeue faild because of redis delete failure: name =$name, id = $id"); 
  77.       } 
  78.     } 
  79.     //解鎖 
  80.     $this->_redis->lock->unlock("Queue:$name"); 
  81.  
  82.     return $result; 
  83.   } 
  84.  
  85.   /** 
  86.    * 獲取隊列頂部若干個Task 并將其出隊 
  87.    * @param [type] $name  隊列名稱 
  88.    * @param integer $count  數量 
  89.    * @param integer $timeout 超時時間 
  90.    * @return [type]      返回數組[0=>['id'=> , 'score'=> ], 1=>['id'=> , 'score'=> ], 2=>['id'=> , 'score'=> ]] 
  91.    */ 
  92.   public function pop($name, $count = 1, $timeout = 10) { 
  93.     //合法性檢測 
  94.     if (empty($name) || $count <= 0) return []; 
  95.      
  96.     //加鎖 
  97.     if (!$this->_redis->lock->lock("Queue:$name")) { 
  98.       Logger::get('queue')->error("pop faild because of pop failure: name = $name, count = $count"); 
  99.       return false
  100.     } 
  101.      
  102.     //取出若干的Task 
  103.     $result = []; 
  104.     $array = $this->_redis->zset->getByScore("Queue:$name"false, microtime(true), truefalse, [0, $count]); 
  105.  
  106.     //將其放在$result數組里 并 刪除掉redis對應的id 
  107.     foreach ($array as $id => $score) { 
  108.       $result[] = ['id'=>$id, 'score'=>$score]; 
  109.       $this->_redis->zset->delete("Queue:$name", $id); 
  110.     } 
  111.  
  112.     //解鎖 
  113.     $this->_redis->lock->unlock("Queue:$name"); 
  114.  
  115.     return $count == 1 ? (empty($result) ? false : $result[0]) : $result; 
  116.   } 
  117.  
  118.   /** 
  119.    * 獲取隊列頂部的若干個Task 
  120.    * @param [type] $name 隊列名稱 
  121.    * @param integer $count 數量 
  122.    * @return [type]     返回數組[0=>['id'=> , 'score'=> ], 1=>['id'=> , 'score'=> ], 2=>['id'=> , 'score'=> ]] 
  123.    */ 
  124.   public function top($name, $count = 1) { 
  125.     //合法性檢測 
  126.     if (empty($name) || $count < 1) return []; 
  127.  
  128.     //取錯若干個Task 
  129.     $result = []; 
  130.     $array = $this->_redis->zset->getByScore("Queue:$name"false, microtime(true), truefalse, [0, $count]); 
  131.      
  132.     //將Task存放在數組里 
  133.     foreach ($array as $id => $score) { 
  134.       $result[] = ['id'=>$id, 'score'=>$score]; 
  135.     } 
  136.  
  137.     //返回數組 
  138.     return $count == 1 ? (empty($result) ? false : $result[0]) : $result;    
  139.   } 

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

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

  1. /** 
  2.  *在redis上實現分布式鎖 
  3.  */ 
  4. class RedisLock { 
  5.   private $redisString; 
  6.   private $lockedNames = []; 
  7.  
  8.   public function __construct($param = NULL) { 
  9.     $this->redisString = RedisFactory::get($param)->string; 
  10.   } 
  11.  
  12.   /** 
  13.    * 加鎖 
  14.    * @param [type] $name      鎖的標識名 
  15.    * @param integer $timeout    循環獲取鎖的等待超時時間,在此時間內會一直嘗試獲取鎖直到超時,為0表示失敗后直接返回不等待 
  16.    * @param integer $expire     當前鎖的最大生存時間(秒),必須大于0,如果超過生存時間鎖仍未被釋放,則系統會自動強制釋放 
  17.    * @param integer $waitIntervalUs 獲取鎖失敗后掛起再試的時間間隔(微秒) 
  18.    * @return [type]         [description] 
  19.    */ 
  20.   public function lock($name, $timeout = 0, $expire = 15, $waitIntervalUs = 100000) { 
  21.     if ($name == nullreturn false
  22.  
  23.     //取得當前時間 
  24.     $now = time(); 
  25.     //獲取鎖失敗時的等待超時時刻 
  26.     $timeoutAt = $now + $timeout; 
  27.     //鎖的最大生存時刻 
  28.     $expireAt = $now + $expire; 
  29.  
  30.     $redisKey = "Lock:{$name}"
  31.     while (true) { 
  32.       //將rediskey的最大生存時刻存到redis里,過了這個時刻該鎖會被自動釋放 
  33.       $result = $this->redisString->setnx($redisKey, $expireAt); 
  34.  
  35.       if ($result != false) { 
  36.         //設置key的失效時間 
  37.         $this->redisString->expire($redisKey, $expireAt); 
  38.         //將鎖標志放到lockedNames數組里 
  39.         $this->lockedNames[$name] = $expireAt; 
  40.         return true
  41.       } 
  42.  
  43.       //以秒為單位,返回給定key的剩余生存時間 
  44.       $ttl = $this->redisString->ttl($redisKey); 
  45.  
  46.       //ttl小于0 表示key上沒有設置生存時間(key是不會不存在的,因為前面setnx會自動創建) 
  47.       //如果出現這種狀況,那就是進程的某個實例setnx成功后 crash 導致緊跟著的expire沒有被調用 
  48.       //這時可以直接設置expire并把鎖納為己用 
  49.       if ($ttl < 0) { 
  50.         $this->redisString->set($redisKey, $expireAt); 
  51.         $this->lockedNames[$name] = $expireAt; 
  52.         return true
  53.       } 
  54.  
  55.       /*****循環請求鎖部分*****/ 
  56.       //如果沒設置鎖失敗的等待時間 或者 已超過最大等待時間了,那就退出 
  57.       if ($timeout <= 0 || $timeoutAt < microtime(true)) break
  58.  
  59.       //隔 $waitIntervalUs 后繼續 請求 
  60.       usleep($waitIntervalUs); 
  61.  
  62.     } 
  63.  
  64.     return false
  65.   } 
  66.  
  67.   /** 
  68.    * 解鎖 
  69.    * @param [type] $name [description] 
  70.    * @return [type]    [description] 
  71.    */ 
  72.   public function unlock($name) { 
  73.     //先判斷是否存在此鎖 
  74.     if ($this->isLocking($name)) { 
  75.       //刪除鎖 
  76.       if ($this->redisString->deleteKey("Lock:$name")) { 
  77.         //清掉lockedNames里的鎖標志 
  78.         unset($this->lockedNames[$name]); 
  79.         return true
  80.       } 
  81.     } 
  82.     return false
  83.   } 
  84.  
  85.   /** 
  86.    * 釋放當前所有獲得的鎖 
  87.    * @return [type] [description] 
  88.    */ 
  89.   public function unlockAll() { 
  90.     //此標志是用來標志是否釋放所有鎖成功 
  91.     $allSuccess = true
  92.     foreach ($this->lockedNames as $name => $expireAt) { 
  93.       if (false === $this->unlock($name)) { 
  94.         $allSuccess = false;  
  95.       } 
  96.     } 
  97.     return $allSuccess; 
  98.   } 
  99.  
  100.   /** 
  101.    * 給當前所增加指定生存時間,必須大于0 
  102.    * @param [type] $name [description] 
  103.    * @return [type]    [description] 
  104.    */ 
  105.   public function expire($name, $expire) { 
  106.     //先判斷是否存在該鎖 
  107.     if ($this->isLocking($name)) { 
  108.       //所指定的生存時間必須大于0 
  109.       $expire = max($expire, 1); 
  110.       //增加鎖生存時間 
  111.       if ($this->redisString->expire("Lock:$name", $expire)) { 
  112.         return true
  113.       } 
  114.     } 
  115.     return false
  116.   } 
  117.  
  118.   /** 
  119.    * 判斷當前是否擁有指定名字的所 
  120.    * @param [type] $name [description] 
  121.    * @return boolean    [description] 
  122.    */ 
  123.   public function isLocking($name) { 
  124.     //先看lonkedName[$name]是否存在該鎖標志名 
  125.     if (isset($this->lockedNames[$name])) { 
  126.       //從redis返回該鎖的生存時間 
  127.       return (string)$this->lockedNames[$name] = (string)$this->redisString->get("Lock:$name"); 
  128.     } 
  129.  
  130.     return false
  131.   } 
  132.  
  133.  
  134. /** 
  135.  * 任務隊列 
  136.  */ 
  137. class RedisQueue { 
  138.   private $_redis; 
  139.  
  140.   public function __construct($param = null) { 
  141.     $this->_redis = RedisFactory::get($param); 
  142.   } 
  143.  
  144.   /** 
  145.    * 入隊一個 Task 
  146.    * @param [type] $name     隊列名稱 
  147.    * @param [type] $id      任務id(或者其數組) 
  148.    * @param integer $timeout    入隊超時時間(秒) 
  149.    * @param integer $afterInterval [description] 
  150.    * @return [type]         [description] 
  151.    */ 
  152.   public function enqueue($name, $id, $timeout = 10, $afterInterval = 0) { 
  153.     //合法性檢測 
  154.     if (empty($name) || empty($id) || $timeout <= 0) return false
  155.  
  156.     //加鎖 
  157.     if (!$this->_redis->lock->lock("Queue:{$name}", $timeout)) { 
  158.       Logger::get('queue')->error("enqueue faild becouse of lock failure: name = $name, id = $id"); 
  159.       return false
  160.     } 
  161.      
  162.     //入隊時以當前時間戳作為 score 
  163.     $score = microtime(true) + $afterInterval; 
  164.     //入隊 
  165.     foreach ((array)$id as $item) { 
  166.       //先判斷下是否已經存在該id了 
  167.       if (false === $this->_redis->zset->getScore("Queue:$name", $item)) { 
  168.         $this->_redis->zset->add("Queue:$name", $score, $item); 
  169.       } 
  170.     } 
  171.      
  172.     //解鎖 
  173.     $this->_redis->lock->unlock("Queue:$name"); 
  174.  
  175.     return true
  176.  
  177.   } 
  178.  
  179.   /** 
  180.    * 出隊一個Task,需要指定$id 和 $score 
  181.    * 如果$score 與隊列中的匹配則出隊,否則認為該Task已被重新入隊過,當前操作按失敗處理 
  182.    * 
  183.    * @param [type] $name  隊列名稱 
  184.    * @param [type] $id   任務標識 
  185.    * @param [type] $score  任務對應score,從隊列中獲取任務時會返回一個score,只有$score和隊列中的值匹配時Task才會被出隊 
  186.    * @param integer $timeout 超時時間(秒) 
  187.    * @return [type]      Task是否成功,返回false可能是redis操作失敗,也有可能是$score與隊列中的值不匹配(這表示該Task自從獲取到本地之后被其他線程入隊過) 
  188.    */ 
  189.   public function dequeue($name, $id, $score, $timeout = 10) { 
  190.     //合法性檢測 
  191.     if (empty($name) || empty($id) || empty($score)) return false
  192.      
  193.     //加鎖 
  194.     if (!$this->_redis->lock->lock("Queue:$name", $timeout)) { 
  195.       Logger:get('queue')->error("dequeue faild becouse of lock lailure:name=$name, id = $id"); 
  196.       return false
  197.     } 
  198.      
  199.     //出隊 
  200.     //先取出redis的score 
  201.     $serverScore = $this->_redis->zset->getScore("Queue:$name", $id); 
  202.     $result = false
  203.     //先判斷傳進來的score和redis的score是否是一樣 
  204.     if ($serverScore == $score) { 
  205.       //刪掉該$id 
  206.       $result = (float)$this->_redis->zset->delete("Queue:$name", $id); 
  207.       if ($result == false) { 
  208.         Logger::get('queue')->error("dequeue faild because of redis delete failure: name =$name, id = $id"); 
  209.       } 
  210.     } 
  211.     //解鎖 
  212.     $this->_redis->lock->unlock("Queue:$name"); 
  213.  
  214.     return $result; 
  215.   } 
  216.  
  217.   /** 
  218.    * 獲取隊列頂部若干個Task 并將其出隊 
  219.    * @param [type] $name  隊列名稱 
  220.    * @param integer $count  數量 
  221.    * @param integer $timeout 超時時間 
  222.    * @return [type]      返回數組[0=>['id'=> , 'score'=> ], 1=>['id'=> , 'score'=> ], 2=>['id'=> , 'score'=> ]] 
  223.    */ 
  224.   public function pop($name, $count = 1, $timeout = 10) { 
  225.     //合法性檢測 
  226.     if (empty($name) || $count <= 0) return []; 
  227.      
  228.     //加鎖 
  229.     if (!$this->_redis->lock->lock("Queue:$name")) { 
  230.       Logger::get('queue')->error("pop faild because of pop failure: name = $name, count = $count"); 
  231.       return false
  232.     } 
  233.      
  234.     //取出若干的Task 
  235.     $result = []; 
  236.     $array = $this->_redis->zset->getByScore("Queue:$name"false, microtime(true), truefalse, [0, $count]); 
  237.  
  238.     //將其放在$result數組里 并 刪除掉redis對應的id 
  239.     foreach ($array as $id => $score) { 
  240.       $result[] = ['id'=>$id, 'score'=>$score]; 
  241.       $this->_redis->zset->delete("Queue:$name", $id); 
  242.     } 
  243.  
  244.     //解鎖 
  245.     $this->_redis->lock->unlock("Queue:$name"); 
  246.  
  247.     return $count == 1 ? (empty($result) ? false : $result[0]) : $result; 
  248.   } 
  249.  
  250.   /** 
  251.    * 獲取隊列頂部的若干個Task 
  252.    * @param [type] $name 隊列名稱 
  253.    * @param integer $count 數量 
  254.    * @return [type]     返回數組[0=>['id'=> , 'score'=> ], 1=>['id'=> , 'score'=> ], 2=>['id'=> , 'score'=> ]] 
  255.    */ 
  256.   public function top($name, $count = 1) { 
  257.     //合法性檢測 
  258.     if (empty($name) || $count < 1) return []; 
  259.  
  260.     //取錯若干個Task 
  261.     $result = []; 
  262.     $array = $this->_redis->zset->getByScore("Queue:$name"false, microtime(true), truefalse, [0, $count]); 
  263.      
  264.     //將Task存放在數組里 
  265.     foreach ($array as $id => $score) { 
  266.       $result[] = ['id'=>$id, 'score'=>$score]; 
  267.     } 
  268.  
  269.     //返回數組 
  270.     return $count == 1 ? (empty($result) ? false : $result[0]) : $result;    
  271.   } 

以上就是本文的全部內容,希望對大家的學習有所幫助。

延伸 · 閱讀

精彩推薦
  • RedisRedis 事務知識點相關總結

    Redis 事務知識點相關總結

    這篇文章主要介紹了Redis 事務相關總結,幫助大家更好的理解和學習使用Redis,感興趣的朋友可以了解下...

    AsiaYe8232021-07-28
  • Redisredis實現排行榜功能

    redis實現排行榜功能

    排行榜在很多地方都能使用到,redis的zset可以很方便地用來實現排行榜功能,本文就來簡單的介紹一下如何使用,具有一定的參考價值,感興趣的小伙伴們...

    乘月歸5022021-08-05
  • Redis詳解Redis復制原理

    詳解Redis復制原理

    與大多數db一樣,Redis也提供了復制機制,以滿足故障恢復和負載均衡等需求。復制也是Redis高可用的基礎,哨兵和集群都是建立在復制基礎上實現高可用的...

    李留廣10222021-08-09
  • RedisRedis如何實現數據庫讀寫分離詳解

    Redis如何實現數據庫讀寫分離詳解

    Redis的主從架構,能幫助我們實現讀多,寫少的情況,下面這篇文章主要給大家介紹了關于Redis如何實現數據庫讀寫分離的相關資料,文中通過示例代碼介紹...

    羅兵漂流記6092019-11-11
  • RedisRedis的配置、啟動、操作和關閉方法

    Redis的配置、啟動、操作和關閉方法

    今天小編就為大家分享一篇Redis的配置、啟動、操作和關閉方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧 ...

    大道化簡5312019-11-14
  • RedisRedis全量復制與部分復制示例詳解

    Redis全量復制與部分復制示例詳解

    這篇文章主要給大家介紹了關于Redis全量復制與部分復制的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用Redis爬蟲具有一定的參考學習...

    豆子先生5052019-11-27
  • Redisredis 交集、并集、差集的具體使用

    redis 交集、并集、差集的具體使用

    這篇文章主要介紹了redis 交集、并集、差集的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友...

    xiaojin21cen10152021-07-27
  • Redisredis中如何使用lua腳本讓你的靈活性提高5個逼格詳解

    redis中如何使用lua腳本讓你的靈活性提高5個逼格詳解

    這篇文章主要給大家介紹了關于redis中如何使用lua腳本讓你的靈活性提高5個逼格的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具...

    一線碼農5812019-11-18
主站蜘蛛池模板: 日韩免费视频一区 | 亚洲国产成人99精品激情在线 | 国产毛片一级aaaaa片 | 五月一区二区久久综合天堂 | 久久99精国产一区二区三区四区 | 青青草国产精品久久久久 | 国产精品猎奇系列在线观看 | 国产激情一区二区三区四区 | a级黄色视屏 | 国产玖玖在线 | 60岁妇女毛片免费观看 | 99久久精品在免费线18 | 国语自产自拍秒拍在线视频 | 98成人| 国产三级精品播放 | 亚洲精品丝袜在线一区波多野结衣 | 亚洲 日韩 自拍 视频一区 | 朝鲜女人free性xxe | 色婷婷久久综合中文久久一本` | 全日本爽视频在线 | 精品久久免费观看 | 四虎最新永久在线精品免费 | 精品久久99麻豆蜜桃666 | 国产精品九九免费视频 | 免费特黄视频 | 亚洲 日韩 国产 制服 在线 | 国产精品吹潮香蕉在线观看 | 国产精品久久久久久爽爽爽 | 精品国产国产综合精品 | 九草在线视频 | 高清一级片 | 亚洲国产精品福利片在线观看 | 999导航| 精品久久久久久久久久久久久久久 | 操碰91| 娇妻被老外疯狂调教 | 轻轻操在线视频 | 亚洲 另类 欧美 变态屎尿 | 草莓视频看污 | 亚洲精品动漫在线观看 | 久青草国产观看在线视频 |