认识 Redis 的发布订阅功能
关于 Redis 发布订阅的功能介绍可以参考:订阅与发布。下面我来介绍下 Redis 发布订阅功能的特性和适用场景。
Redis 发布订阅功能的特性
- 消息的发送者与接收者之间通过 channel 绑定:channel 可以是确定的字符串,也可以基于模式匹配
- 客户端可以订阅任意多个 channel
- 发送者发送的消息无法持久化,所以可能会造成消息丢失
- 由于消息无法持久化,所以,消费者无法收到在订阅 channel 之间发送的消息
- 发送者与客户端之间的消息发送与接收不存在 ACK 机制
Redis 发布订阅功能的适用场景
由于没有消息持久化与 ACK 的保证,所以,Redis 的发布订阅功能并不可靠。这也就导致了它的应用场景很有限,建议用于实时与可靠性要求不高的场景。例如:
- 消息推送
- 内网环境的消息通知
- ...
总之,Redis 发布订阅功能足够简单,如果没有过多的要求,且不想搭建 Kafka、RabbitMQ 这样的可靠型消息系统时,可以考虑尝试使用 Redis。
Redis 发布订阅功能在 SpringBoot 中的关键类
SpringBoot 版本
<parent>
Spring Data Redis 实现发布订阅功能非常简单,只有这样的几个类:Topic、MessageListener、RedisMessageListenerContainer。下面对它们进行解释:
org.springframework.data.redis.listener.Topic
消息发送者与接收者之间的 channel 定义,有两个实现类: org.springframework.data.redis.listener.ChannelTopic:一个确定的字符串 org.springframework.data.redis.listener.PatternTopic:基于模式匹配
org.springframework.data.redis.connection.MessageListener
一个回调接口,消息监听器,用于接收发送到 channel 的消息,接口定义如下:
package
org.springframework.data.redis.listener.RedisMessageListenerContainer
用于消息监听,需要将 Topic 和 MessageListener 注册到 RedisMessageListenerContainer 中。这样,当 Topic 上有消息时,由 RedisMessageListenerContainer 通知 MessageListener,客户端通过 onMessage 拿到消息后,自行处理。
Redis 发布订阅功能在 SpringBoot 中的实践
说明:当前给出的示例代码使用 ChannelTopic,可以自行测试使用 PatternTopic。
- VO 对象定义:CityInfo
import
- 配置类定义:RedisConfig
import
- MessageListener 接口实现类:SubscribeListener
import
- 测试用例:RedisPubSubTest
import
执行测试用例,可以看到如下打印信息:
2019