一、前言
雙十一剛過不久,大家都知道在天貓、京東、蘇寧等等電商網站上有很多秒殺活動,例如在某一個時刻搶購一個原價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 后繼續 請求。 這就是加鎖的整一個代碼分析。
/**
* 加鎖
* @param [type] $name 鎖的標識名
* @param integer $timeout 循環獲取鎖的等待超時時間,在此時間內會一直嘗試獲取鎖直到超時,為0表示失敗后直接返回不等待
* @param integer $expire 當前鎖的最大生存時間(秒),必須大于0,如果超過生存時間鎖仍未被釋放,則系統會自動強制釋放
* @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) {
//設置key的失效時間
$this->redisString->expire($redisKey, $expireAt);
//將鎖標志放到lockedNames數組里
$this->lockedNames[$name] = $expireAt;
return true;
}
//以秒為單位,返回給定key的剩余生存時間
$ttl = $this->redisString->ttl($redisKey);
//ttl小于0 表示key上沒有設置生存時間(key是不會不存在的,因為前面setnx會自動創建)
//如果出現這種狀況,那就是進程的某個實例setnx成功后 crash 導致緊跟著的expire沒有被調用
//這時可以直接設置expire并把鎖納為己用
if ($ttl 0) {
$this->redisString->set($redisKey, $expireAt);
$this->lockedNames[$name] = $expireAt;
return true;
}
/*****循環請求鎖部分*****/
//如果沒設置鎖失敗的等待時間 或者 已超過最大等待時間了,那就退出
if ($timeout = 0 || $timeoutAt microtime(true)) break;
//隔 $waitIntervalUs 后繼續 請求
usleep($waitIntervalUs);
}
return false;
}
接著看解鎖的代碼分析:解鎖就簡單多了,傳入參數就是鎖標識,先是判斷是否存在該鎖,存在的話,就從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;
}
在貼上刪除掉所有鎖的方法,其實都一個樣,多了個循環遍歷而已。
/**
* 釋放當前所有獲得的鎖
* @return [type] [description]
*/
public function unlockAll() {
//此標志是用來標志是否釋放所有鎖成功
$allSuccess = true;
foreach ($this->lockedNames as $name => $expireAt) {
if (false === $this->unlock($name)) {
$allSuccess = false;
}
}
return $allSuccess;
}
以上就是用Redis實現分布式鎖的整一套思路和代碼實現的總結和分享,這里我附上正一個實現類的代碼,代碼里我基本上對每一行進行了注釋,方便大家快速看懂并且能模擬應用。想要深入了解的請看整個類的代碼:
/**
*在redis上實現分布式鎖
*/
class RedisLock {
private $redisString;
private $lockedNames = [];
public function __construct($param = NULL) {
$this->redisString = RedisFactory::get($param)->string;
}
/**
* 加鎖
* @param [type] $name 鎖的標識名
* @param integer $timeout 循環獲取鎖的等待超時時間,在此時間內會一直嘗試獲取鎖直到超時,為0表示失敗后直接返回不等待
* @param integer $expire 當前鎖的最大生存時間(秒),必須大于0,如果超過生存時間鎖仍未被釋放,則系統會自動強制釋放
* @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) {
//設置key的失效時間
$this->redisString->expire($redisKey, $expireAt);
//將鎖標志放到lockedNames數組里
$this->lockedNames[$name] = $expireAt;
return true;
}
//以秒為單位,返回給定key的剩余生存時間
$ttl = $this->redisString->ttl($redisKey);
//ttl小于0 表示key上沒有設置生存時間(key是不會不存在的,因為前面setnx會自動創建)
//如果出現這種狀況,那就是進程的某個實例setnx成功后 crash 導致緊跟著的expire沒有被調用
//這時可以直接設置expire并把鎖納為己用
if ($ttl 0) {
$this->redisString->set($redisKey, $expireAt);
$this->lockedNames[$name] = $expireAt;
return true;
}
/*****循環請求鎖部分*****/
//如果沒設置鎖失敗的等待時間 或者 已超過最大等待時間了,那就退出
if ($timeout = 0 || $timeoutAt microtime(true)) break;
//隔 $waitIntervalUs 后繼續 請求
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實現任務隊列的代碼分析
(1)任務隊列,用于將業務邏輯中可以異步處理的操作放入隊列中,在其他線程中處理后出隊
(2)隊列中使用了分布式鎖和其他邏輯,保證入隊和出隊的一致性
(3)這個隊列和普通隊列不一樣,入隊時的id是用來區分重復入隊的,隊列里面只會有一條記錄,同一個id后入的覆蓋前入的,而不是追加, 如果需求要求重復入隊當做不用的任務,請使用不同的id區分
先看入隊的代碼分析:首先當然是對參數的合法性檢測,接著就用到上面加鎖機制的內容了,就是開始加鎖,入隊時我這里選擇當前時間戳作為score,接著就是入隊了,使用的是zset數據結構的add()方法,入隊完成后,就對該任務解鎖,即完成了一個入隊的操作。
/**
* 入隊一個 Task
* @param [type] $name 隊列名稱
* @param [type] $id 任務id(或者其數組)
* @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) {
//先判斷下是否已經存在該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已被重新入隊過,當前操作按失敗處理。首先和對參數進行合法性檢測,接著又用到加鎖的功能了,然后及時出隊了,先使用getScore()從Redis里獲取到該id的score,然后將傳入的$score和Redis里存儲的score進行對比,如果兩者相等就進行出隊操作,也就是使用zset里的delete()方法刪掉該任務id,最后當前就是解鎖了。這就是出隊的代碼分析。
/**
* 出隊一個Task,需要指定$id 和 $score
* 如果$score 與隊列中的匹配則出隊,否則認為該Task已被重新入隊過,當前操作按失敗處理
*
* @param [type] $name 隊列名稱
* @param [type] $id 任務標識
* @param [type] $score 任務對應score,從隊列中獲取任務時會返回一個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 并將其出隊的方法,想了解的朋友可以看這段代碼,假如看不太明白就留言,這里我不再對其進行分析了。
/**
* 獲取隊列頂部若干個Task 并將其出隊
* @param [type] $name 隊列名稱
* @param integer $count 數量
* @param integer $timeout 超時時間
* @return [type] 返回數組[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數組里 并 刪除掉redis對應的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實現任務隊列的整一套思路和代碼實現的總結和分享,這里我附上正一個實現類的代碼,代碼里我基本上對每一行進行了注釋,方便大家快速看懂并且能模擬應用。想要深入了解的請看整個類的代碼:
/**
* 任務隊列
*
*/
class RedisQueue {
private $_redis;
public function __construct($param = null) {
$this->_redis = RedisFactory::get($param);
}
/**
* 入隊一個 Task
* @param [type] $name 隊列名稱
* @param [type] $id 任務id(或者其數組)
* @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) {
//先判斷下是否已經存在該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 任務標識
* @param [type] $score 任務對應score,從隊列中獲取任務時會返回一個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 數量
* @param integer $timeout 超時時間
* @return [type] 返回數組[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數組里 并 刪除掉redis對應的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 數量
* @return [type] 返回數組[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存放在數組里
foreach ($array as $id => $score) {
$result[] = ['id'=>$id, 'score'=>$score];
}
//返回數組
return $count == 1 ? (empty($result) ? false : $result[0]) : $result;
}
}
到此,這兩大塊功能基本講解完畢,對于任務隊列,你可以寫一個shell腳本,讓服務器定時運行某些程序,實現入隊出隊等操作,這里我就不在將其與實際應用結合起來去實現了,大家理解好這兩大功能的實現思路即可,由于代碼用的是PHP語言來寫的,如果你理解了實現思路,你完全可以使用java或者是.net等等其他語言去實現這兩個功能。這兩大功能的應用場景十分多,特別是秒殺,另一個就是春運搶火車票,這兩個是最鮮明的例子了。當然還有很多地方用到,這里我不再一一列舉。
好了,本次總結和分享到此完畢。最后我附上分布式鎖和任務隊列這兩個類:
/**
*在redis上實現分布式鎖
*/
class RedisLock {
private $redisString;
private $lockedNames = [];
public function __construct($param = NULL) {
$this->redisString = RedisFactory::get($param)->string;
}
/**
* 加鎖
* @param [type] $name 鎖的標識名
* @param integer $timeout 循環獲取鎖的等待超時時間,在此時間內會一直嘗試獲取鎖直到超時,為0表示失敗后直接返回不等待
* @param integer $expire 當前鎖的最大生存時間(秒),必須大于0,如果超過生存時間鎖仍未被釋放,則系統會自動強制釋放
* @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) {
//設置key的失效時間
$this->redisString->expire($redisKey, $expireAt);
//將鎖標志放到lockedNames數組里
$this->lockedNames[$name] = $expireAt;
return true;
}
//以秒為單位,返回給定key的剩余生存時間
$ttl = $this->redisString->ttl($redisKey);
//ttl小于0 表示key上沒有設置生存時間(key是不會不存在的,因為前面setnx會自動創建)
//如果出現這種狀況,那就是進程的某個實例setnx成功后 crash 導致緊跟著的expire沒有被調用
//這時可以直接設置expire并把鎖納為己用
if ($ttl 0) {
$this->redisString->set($redisKey, $expireAt);
$this->lockedNames[$name] = $expireAt;
return true;
}
/*****循環請求鎖部分*****/
//如果沒設置鎖失敗的等待時間 或者 已超過最大等待時間了,那就退出
if ($timeout = 0 || $timeoutAt microtime(true)) break;
//隔 $waitIntervalUs 后繼續 請求
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;
}
}
/**
* 任務隊列
*/
class RedisQueue {
private $_redis;
public function __construct($param = null) {
$this->_redis = RedisFactory::get($param);
}
/**
* 入隊一個 Task
* @param [type] $name 隊列名稱
* @param [type] $id 任務id(或者其數組)
* @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) {
//先判斷下是否已經存在該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 任務標識
* @param [type] $score 任務對應score,從隊列中獲取任務時會返回一個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 數量
* @param integer $timeout 超時時間
* @return [type] 返回數組[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數組里 并 刪除掉redis對應的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 數量
* @return [type] 返回數組[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存放在數組里
foreach ($array as $id => $score) {
$result[] = ['id'=>$id, 'score'=>$score];
}
//返回數組
return $count == 1 ? (empty($result) ? false : $result[0]) : $result;
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助。
您可能感興趣的文章:- redis中使用java腳本實現分布式鎖
- Redis實現分布式鎖的幾種方法總結
- Redis分布式鎖的實現方式(redis面試題)
- Redis分布式鎖實現方式及超時問題解決
- Redis上實現分布式鎖以提高性能的方案研究
- redis實現分布式的方法總結
- Redis分布式非公平鎖的使用