> 文章列表 > redis 发布订阅模式

redis 发布订阅模式

redis 发布订阅模式

Redis有两种发布/订阅模式

基于频道(Channel)的发布/订阅
基于模式(pattern)的发布/订阅

模式的发布订阅
模式与频道的区别,简单理解模式是多个频道的组合。

redis订阅和发布应用场景

redis的订阅发布功能相对轻量,针对数据准确和安全性要求没有那么高可以直接使用。

缓存机制

在一些优化场景下,可能会使用 本地 + 远程 双缓存机制,远程缓存是一套共用的中间件,总共只有一套数据。而 本地缓存就不一样了,如果你部署的是多个实例,那就有多套本地数据,当数据更新了,如何触达这些本地缓存?这个时候,你就可以考虑使用发布订阅模式,消息提供者 - 更新数据的人,消息接收方 - 需要更新本地缓存的服务。

退订频道
UNSUBSCRIBE channel [channel …]

SpringBoot 配置

步骤
1.redis 维护通道与订阅者的关系
2.发布者将消息推送至对应通道
3.redis 将消息转发至与该通道关联的所有订阅者


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;@Configuration
public class RedisSubConfig {@Beanpublic RedisMessageListenerContainer container(RedisConnectionFactory factory, MessageListener listener) {RedisMessageListenerContainer container = new RedisMessageListenerContainer();container.setConnectionFactory(factory);//订阅频道redis.news 和 redis.life 这个container可以添加多个messageListenercontainer.addMessageListener(listener, new ChannelTopic("redis.user"));return container;}
}

其他

关于双端队列机制

redis 的List数据类型结构提供了 blpop 、brpop 命令结合 rpush、lpush 命令可以实现消息队列机制,基于双端链表实现的发布与订阅功能

这种方式存在两个局限性:
1.不能支持一对多的消息分发。
2.如果生产者生成的速度远远大于消费者消费的速度,易堆积大量未消费的消息

解析:双端队列模式只能有一个或多个消费者轮着去消费,却不能将消息同时发给其他消费者
链接:https://blog.csdn.net/w15558056319/article/details/121490953

参考资料

Redis两种发布/订阅模式
https://blog.csdn.net/w15558056319/article/details/121490953

SpringBoot 整合使用Redis发布订阅功能
https://blog.csdn.net/congge_study/article/details/126686318

Spring Boot Redis使用发布订阅模式
https://blog.csdn.net/weixin_42502300/article/details/128254875