发布订阅的概念
发送者(发布者)不是计划发送消息给特定的接收者(订阅者)。而是发布的消息分到不同的频道,不需要知道什么样的订阅者订阅。订阅者对一个或多个频道感兴趣,只需接收感兴趣的消息,不需要知道什么样的发布者发布的。这种发布者和订阅者的解耦合可以带来更大的扩展性和更加动态的网络拓扑。
测试发布订阅功能
help @pubsub
#pubsub提供的方法
PSUBSCRIBE pattern [pattern ...]
summary: Listen for messages published to channels matching the given patterns
since: 2.0.0
PUBLISH channel message
summary: Post a message to a channel
since: 2.0.0
PUBSUB subcommand [argument [argument ...]]
summary: Inspect the state of the Pub/Sub subsystem
since: 2.8.0
PUNSUBSCRIBE [pattern [pattern ...]]
summary: Stop listening for messages posted to channels matching the given patterns
since: 2.0.0
SUBSCRIBE channel [channel ...]
summary: Listen for messages published to the given channels
since: 2.0.0
UNSUBSCRIBE [channel [channel ...]]
summary: Stop listening for messages posted to the given channels
since: 2.0.0
测试代码:消费端需要先监听才可以收到数据
PUBLISH ooxx hello - (integer) 0
#开启另一个redis连接
SUBSCRIBE ooxx #此时没有读到任何信息
PUBLISH ooxx hello - (integer) 1
-client2 获取了hello的数据
发布订阅的应用场景
如果我们使用redis做一套聊天系统,其中有实时数据和历史数据:
1.由于用户可能查询很长时间以前的数据,但是查询的频率是相对较低的,所以全量数据可以使用mysql等数据库保存
2.用户也会查询近期的数据,比如三天之内的数据,我们可以使用sorted_set保存,并使用其中评分的功能对数据做出排序
3.对于聊天的实时数据,我们就可以使用发布订阅了
发布订阅的应用场景
然后我们可以使用发布订阅的功能改善我们的架构:
对于每一个写操作,我们都使用发布订阅功能,写入我们对应的存储区域
使用发布订阅存储数据