redis实现高并发下的抢购/秒杀功能

为了自我学习和交流PHPjQuery,Linux,lamp,shell,JavaScript,服务器)等一系列的知识,希望光临本博客的人可以进来交流。寻求共同发展。搭建平台。本人博客也有许多的技术文档,希望可以为你提供一些帮助。


QQ群: 191848169   点击链接加入群【PHP技术交流(总群)】



这一次总结和分享用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分布式锁和任务队列代码
复制代码
  • 6
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值