用Redis实现分布式锁 与 实现任务队列

时间:2023-03-09 21:18:17
用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 后继续 请求。  这就是加锁的整一个代码分析。

用Redis实现分布式锁 与 实现任务队列
 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实现分布式锁 与 实现任务队列

    接着看解锁的代码分析:解锁就简单多了,传入参数就是锁标识,先是判断是否存在该锁,存在的话,就从redis里面通过deleteKey()函数删除掉锁标识即可。

用Redis实现分布式锁 与 实现任务队列
 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 }
用Redis实现分布式锁 与 实现任务队列

    在贴上删除掉所有锁的方法,其实都一个样,多了个循环遍历而已。

用Redis实现分布式锁 与 实现任务队列
 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 *在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 == null) return 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 }
用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 == null) return 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 }
用Redis实现分布式锁 与 实现任务队列

  (二)用Redis实现任务队列的代码分析

    (1)任务队列,用于将业务逻辑中可以异步处理的操作放入队列中,在其他线程中处理后出队

    (2)队列中使用了分布式锁和其他逻辑,保证入队和出队的一致性

    (3)这个队列和普通队列不一样,入队时的id是用来区分重复入队的,队列里面只会有一条记录,同一个id后入的覆盖前入的,而不是追加, 如果需求要求重复入队当做不用的任务,请使用不同的id区分

    先看入队的代码分析:首先当然是对参数的合法性检测,接着就用到上面加锁机制的内容了,就是开始加锁,入队时我这里选择当前时间戳作为score,接着就是入队了,使用的是zset数据结构的add()方法,入队完成后,就对该任务解锁,即完成了一个入队的操作。

用Redis实现分布式锁 与 实现任务队列
 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 }
用Redis实现分布式锁 与 实现任务队列

    接着来看一下出队的代码分析:出队一个Task,需要指定它的$id 和 $score,如果$score与队列中的匹配则出队,否则认为该Task已被重新入队过,当前操作按失败处理。首先和对参数进行合法性检测,接着又用到加锁的功能了,然后及时出队了,先使用getScore()从Redis里获取到该id的score,然后将传入的$score和Redis里存储的score进行对比,如果两者相等就进行出队操作,也就是使用zset里的delete()方法删掉该任务id,最后当前就是解锁了。这就是出队的代码分析。

用Redis实现分布式锁 与 实现任务队列
 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 }
用Redis实现分布式锁 与 实现任务队列

    学过数据结构这门课的朋友都应该知道,队列操作还有弹出顶部某个值的方法等等,这里处理入队出队操作,我还实现了 获取队列顶部若干个Task 并将其出队的方法,想了解的朋友可以看这段代码,假如看不太明白就留言,这里我不再对其进行分析了。

用Redis实现分布式锁 与 实现任务队列
 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实现分布式锁 与 实现任务队列

  以上就是用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), true, false, [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), true, false, [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 }
140 }
用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), true, false, [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), true, false, [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 }
140 }
用Redis实现分布式锁 与 实现任务队列

  

  到此,这两大块功能基本讲解完毕,对于任务队列,你可以写一个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 == null) return 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 */
138 class RedisQueue {
139 private $_redis;
140
141 public function __construct($param = null) {
142 $this->_redis = RedisFactory::get($param);
143 }
144
145 /**
146 * 入队一个 Task
147 * @param [type] $name 队列名称
148 * @param [type] $id 任务id(或者其数组)
149 * @param integer $timeout 入队超时时间(秒)
150 * @param integer $afterInterval [description]
151 * @return [type] [description]
152 */
153 public function enqueue($name, $id, $timeout = 10, $afterInterval = 0) {
154 //合法性检测
155 if (empty($name) || empty($id) || $timeout <= 0) return false;
156
157 //加锁
158 if (!$this->_redis->lock->lock("Queue:{$name}", $timeout)) {
159 Logger::get('queue')->error("enqueue faild becouse of lock failure: name = $name, id = $id");
160 return false;
161 }
162
163 //入队时以当前时间戳作为 score
164 $score = microtime(true) + $afterInterval;
165 //入队
166 foreach ((array)$id as $item) {
167 //先判断下是否已经存在该id了
168 if (false === $this->_redis->zset->getScore("Queue:$name", $item)) {
169 $this->_redis->zset->add("Queue:$name", $score, $item);
170 }
171 }
172
173 //解锁
174 $this->_redis->lock->unlock("Queue:$name");
175
176 return true;
177
178 }
179
180 /**
181 * 出队一个Task,需要指定$id 和 $score
182 * 如果$score 与队列中的匹配则出队,否则认为该Task已被重新入队过,当前操作按失败处理
183 *
184 * @param [type] $name 队列名称
185 * @param [type] $id 任务标识
186 * @param [type] $score 任务对应score,从队列中获取任务时会返回一个score,只有$score和队列中的值匹配时Task才会被出队
187 * @param integer $timeout 超时时间(秒)
188 * @return [type] Task是否成功,返回false可能是redis操作失败,也有可能是$score与队列中的值不匹配(这表示该Task自从获取到本地之后被其他线程入队过)
189 */
190 public function dequeue($name, $id, $score, $timeout = 10) {
191 //合法性检测
192 if (empty($name) || empty($id) || empty($score)) return false;
193
194 //加锁
195 if (!$this->_redis->lock->lock("Queue:$name", $timeout)) {
196 Logger:get('queue')->error("dequeue faild becouse of lock lailure:name=$name, id = $id");
197 return false;
198 }
199
200 //出队
201 //先取出redis的score
202 $serverScore = $this->_redis->zset->getScore("Queue:$name", $id);
203 $result = false;
204 //先判断传进来的score和redis的score是否是一样
205 if ($serverScore == $score) {
206 //删掉该$id
207 $result = (float)$this->_redis->zset->delete("Queue:$name", $id);
208 if ($result == false) {
209 Logger::get('queue')->error("dequeue faild because of redis delete failure: name =$name, id = $id");
210 }
211 }
212 //解锁
213 $this->_redis->lock->unlock("Queue:$name");
214
215 return $result;
216 }
217
218 /**
219 * 获取队列顶部若干个Task 并将其出队
220 * @param [type] $name 队列名称
221 * @param integer $count 数量
222 * @param integer $timeout 超时时间
223 * @return [type] 返回数组[0=>['id'=> , 'score'=> ], 1=>['id'=> , 'score'=> ], 2=>['id'=> , 'score'=> ]]
224 */
225 public function pop($name, $count = 1, $timeout = 10) {
226 //合法性检测
227 if (empty($name) || $count <= 0) return [];
228
229 //加锁
230 if (!$this->_redis->lock->lock("Queue:$name")) {
231 Logger::get('queue')->error("pop faild because of pop failure: name = $name, count = $count");
232 return false;
233 }
234
235 //取出若干的Task
236 $result = [];
237 $array = $this->_redis->zset->getByScore("Queue:$name", false, microtime(true), true, false, [0, $count]);
238
239 //将其放在$result数组里 并 删除掉redis对应的id
240 foreach ($array as $id => $score) {
241 $result[] = ['id'=>$id, 'score'=>$score];
242 $this->_redis->zset->delete("Queue:$name", $id);
243 }
244
245 //解锁
246 $this->_redis->lock->unlock("Queue:$name");
247
248 return $count == 1 ? (empty($result) ? false : $result[0]) : $result;
249 }
250
251 /**
252 * 获取队列顶部的若干个Task
253 * @param [type] $name 队列名称
254 * @param integer $count 数量
255 * @return [type] 返回数组[0=>['id'=> , 'score'=> ], 1=>['id'=> , 'score'=> ], 2=>['id'=> , 'score'=> ]]
256 */
257 public function top($name, $count = 1) {
258 //合法性检测
259 if (empty($name) || $count < 1) return [];
260
261 //取错若干个Task
262 $result = [];
263 $array = $this->_redis->zset->getByScore("Queue:$name", false, microtime(true), true, false, [0, $count]);
264
265 //将Task存放在数组里
266 foreach ($array as $id => $score) {
267 $result[] = ['id'=>$id, 'score'=>$score];
268 }
269
270 //返回数组
271 return $count == 1 ? (empty($result) ? false : $result[0]) : $result;
272 }
273 }
用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 == null) return 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 */
138 class RedisQueue {
139 private $_redis;
140
141 public function __construct($param = null) {
142 $this->_redis = RedisFactory::get($param);
143 }
144
145 /**
146 * 入队一个 Task
147 * @param [type] $name 队列名称
148 * @param [type] $id 任务id(或者其数组)
149 * @param integer $timeout 入队超时时间(秒)
150 * @param integer $afterInterval [description]
151 * @return [type] [description]
152 */
153 public function enqueue($name, $id, $timeout = 10, $afterInterval = 0) {
154 //合法性检测
155 if (empty($name) || empty($id) || $timeout <= 0) return false;
156
157 //加锁
158 if (!$this->_redis->lock->lock("Queue:{$name}", $timeout)) {
159 Logger::get('queue')->error("enqueue faild becouse of lock failure: name = $name, id = $id");
160 return false;
161 }
162
163 //入队时以当前时间戳作为 score
164 $score = microtime(true) + $afterInterval;
165 //入队
166 foreach ((array)$id as $item) {
167 //先判断下是否已经存在该id了
168 if (false === $this->_redis->zset->getScore("Queue:$name", $item)) {
169 $this->_redis->zset->add("Queue:$name", $score, $item);
170 }
171 }
172
173 //解锁
174 $this->_redis->lock->unlock("Queue:$name");
175
176 return true;
177
178 }
179
180 /**
181 * 出队一个Task,需要指定$id 和 $score
182 * 如果$score 与队列中的匹配则出队,否则认为该Task已被重新入队过,当前操作按失败处理
183 *
184 * @param [type] $name 队列名称
185 * @param [type] $id 任务标识
186 * @param [type] $score 任务对应score,从队列中获取任务时会返回一个score,只有$score和队列中的值匹配时Task才会被出队
187 * @param integer $timeout 超时时间(秒)
188 * @return [type] Task是否成功,返回false可能是redis操作失败,也有可能是$score与队列中的值不匹配(这表示该Task自从获取到本地之后被其他线程入队过)
189 */
190 public function dequeue($name, $id, $score, $timeout = 10) {
191 //合法性检测
192 if (empty($name) || empty($id) || empty($score)) return false;
193
194 //加锁
195 if (!$this->_redis->lock->lock("Queue:$name", $timeout)) {
196 Logger:get('queue')->error("dequeue faild becouse of lock lailure:name=$name, id = $id");
197 return false;
198 }
199
200 //出队
201 //先取出redis的score
202 $serverScore = $this->_redis->zset->getScore("Queue:$name", $id);
203 $result = false;
204 //先判断传进来的score和redis的score是否是一样
205 if ($serverScore == $score) {
206 //删掉该$id
207 $result = (float)$this->_redis->zset->delete("Queue:$name", $id);
208 if ($result == false) {
209 Logger::get('queue')->error("dequeue faild because of redis delete failure: name =$name, id = $id");
210 }
211 }
212 //解锁
213 $this->_redis->lock->unlock("Queue:$name");
214
215 return $result;
216 }
217
218 /**
219 * 获取队列顶部若干个Task 并将其出队
220 * @param [type] $name 队列名称
221 * @param integer $count 数量
222 * @param integer $timeout 超时时间
223 * @return [type] 返回数组[0=>['id'=> , 'score'=> ], 1=>['id'=> , 'score'=> ], 2=>['id'=> , 'score'=> ]]
224 */
225 public function pop($name, $count = 1, $timeout = 10) {
226 //合法性检测
227 if (empty($name) || $count <= 0) return [];
228
229 //加锁
230 if (!$this->_redis->lock->lock("Queue:$name")) {
231 Logger::get('queue')->error("pop faild because of pop failure: name = $name, count = $count");
232 return false;
233 }
234
235 //取出若干的Task
236 $result = [];
237 $array = $this->_redis->zset->getByScore("Queue:$name", false, microtime(true), true, false, [0, $count]);
238
239 //将其放在$result数组里 并 删除掉redis对应的id
240 foreach ($array as $id => $score) {
241 $result[] = ['id'=>$id, 'score'=>$score];
242 $this->_redis->zset->delete("Queue:$name", $id);
243 }
244
245 //解锁
246 $this->_redis->lock->unlock("Queue:$name");
247
248 return $count == 1 ? (empty($result) ? false : $result[0]) : $result;
249 }
250
251 /**
252 * 获取队列顶部的若干个Task
253 * @param [type] $name 队列名称
254 * @param integer $count 数量
255 * @return [type] 返回数组[0=>['id'=> , 'score'=> ], 1=>['id'=> , 'score'=> ], 2=>['id'=> , 'score'=> ]]
256 */
257 public function top($name, $count = 1) {
258 //合法性检测
259 if (empty($name) || $count < 1) return [];
260
261 //取错若干个Task
262 $result = [];
263 $array = $this->_redis->zset->getByScore("Queue:$name", false, microtime(true), true, false, [0, $count]);
264
265 //将Task存放在数组里
266 foreach ($array as $id => $score) {
267 $result[] = ['id'=>$id, 'score'=>$score];
268 }
269
270 //返回数组
271 return $count == 1 ? (empty($result) ? false : $result[0]) : $result;
272 }
273 }

                                                                    __kelly_