Redis-发布订阅

686 阅读1分钟

概念简介

基础了解

  1. Redis的发布订阅是一种消息通信模式
  2. Redis的发布订阅存在三个角色:发布者,订阅者和频道

实现原理

举个通俗易懂的例子:微信公众号

现在有三个角色

  • A代表某个微信公众号(假设为VC)的创建者(发布者)
  • B1,B2,B3....代表订阅VC的人(订阅者)
  • S代表频道,即微信公众号本身。

那他们之间的关系就如下展示

image.png

通过Redis实现简单的发布订阅

发布订阅所用到的命令

image.png

具体操作

实现Redis发布订阅需要开启两个Redis-cli客户端

  1. 订阅端:订阅一个微信公众号VC
127.0.0.1:6379> subscribe VC  # 订阅一个微信公众号VC
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "VC"
3) (integer) 1
  1. 发布者:发布消息
127.0.0.1:6379> publish VC "this is a good artical"  # 发送第一个消息
(integer) 1
127.0.0.1:6379> publish VC "do you like to read it more than once"  # 发送第二个消息
(integer) 1 
127.0.0.1:6379>

这时候再去看订阅端,会发现,接受到了发布者发布的消息

image.png