一.Redis实现队列redis
以前说了,使用lpush 配合rpop 或者rpush配合lpop就能实现队列了.Redis提供了一个方法能够阻塞等待,若是队列里面是空的就阻塞等待.shell
生产者:ui
localhost:6379> lpush queue 5 4 3 2 1
(integer) 5
消费者:spa
localhost:6379> BRPOP queue 0 1) "queue" 2) "5" (67.95s) localhost:6379> BRPOP queue 0 1) "queue" 2) "4" localhost:6379> BRPOP queue 0 1) "queue" 2) "3" localhost:6379> BRPOP queue 0 1) "queue" 2) "2" localhost:6379> BRPOP queue 0 1) "queue" 2) "1" localhost:6379> BRPOP queue 0
brpop key timecode
time为阻塞等待的时间,0表示无限等待队列
队列 queue里面是空的,则会阻塞等待.因为设置的时间为无限等.it
Redis在取队列的时候支持优先级.class
生产者:
channel
localhost:6379> lpush queue:1 5 4 (integer) 2 localhost:6379> lpush queue:2 2 1 0 (integer) 3
消费者:queue
localhost:6379> brpop queue:1 queue:2 10 1) "queue:1" 2) "5" localhost:6379> brpop queue:1 queue:2 10 1) "queue:1" 2) "4" localhost:6379> brpop queue:1 queue:2 10 1) "queue:2" 2) "2" localhost:6379> brpop queue:1 queue:2 10 1) "queue:2" 2) "1" localhost:6379> brpop queue:1 queue:2 10 1) "queue:2" 2) "0" localhost:6379> brpop queue:1 queue:2 10 (nil) (10.32s)
brpop后面放多个队列的时候 前面的队列优先级高.会先取出前面的队列以后在取后面的队列.
二.发布/订阅
全部订阅者均可以收到发布者的内容.也是利用redis的列表实现的.可是发布者发布的内容不会被存储下来,因此若是channel中没有订阅者,则消息直接丢失.
发布者:
localhost:6379> publish channel hi (integer) 0
因为这个时候channel尚未订阅者,因此返回的结果是0.
订阅者:
localhost:6379> subscribe channel Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "channel" 3) (integer) 1
这样每次发布者发布消息以后,全部对这个channel订阅的订阅者都能收到消息.