Redis的发布订阅

Redis发布订阅原理

注意:基本上不会使用redis的发布订阅来使用mq,redis主要还是用来做缓存的。mq市面上已经有了很流行的了。大家可以去了解一下。

Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。

Redis 客户端可以订阅任意数量的频道。

 

下图展示了频道 channel1 , 以及订阅这个频道的三个客户端 —— client2 、 client5 和 client1 之间的关系:

 

当有新消息通过 PUBLISH 命令发送给频道 channel1 时, 这个消息就会被发送给订阅它的三个客户端:

Redis 发布订阅命令

psubscribe pattern [pattern ...]订阅一个或者多个给定模式的频道

 

pubsub subcommand [argument [argument ...]]查看订阅与发布系统状态

 

publish channel messgae将消息发送到指定的频道

 

punsubscribe [pattern [pattern ...]]退订所有给定模式的频道

 

subscribe channel [channel ...]订阅给定的一个或多个频道的信息

 

unsubscribe [channel [channel ...] ]指退订给定的频道

案例

Demo1:

订阅redisChat频道

subscribe redisChat

redisChat频道广播消息

publish redisChat "hello"

消息发送完毕后,订阅方就可以接受到消息了。可以看以下

Demo2: 

订阅多个频道,这里是可以使用*的,表示new1 new2 等等都被订阅了

psubscribe new*

 

广播信息

publish new1 redis1

publish new2 redis1

原文地址:https://www.cnblogs.com/itoyr/p/10069668.html