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