【redis】发布订阅

embedded/2025/3/15 11:04:01/

Redis的发布订阅(Pub/Sub)是一种基于消息多播的通信机制,它允许消息的**发布者(Publisher)向特定频道发送消息,而订阅者(Subscriber)**通过订阅频道或模式来接收消息。

其核心特点如下:

  1. 轻量级:无需额外组件,直接通过Redis服务实现

  2. 实时性:消息即时推送,无轮询延迟

  3. 广播模式:一个消息可被多个订阅者同时接收

  4. 无状态性:不存储历史消息,订阅者只能接收订阅后的消息

发布订阅命令的使用

有关发布订阅的命令可以通过help @pubsub命令来查看。有关命令的使用可以通过help 命令来查看,例如help publish

基础命令速查表

命令作用示例
SUBSCRIBE订阅一个或多个频道SUBSCRIBE news sports
PSUBSCRIBE使用模式匹配订阅频道PSUBSCRIBE sensor.*
PUBLISH向指定频道发送消息PUBLISH news "Hello"
UNSUBSCRIBE退订指定频道UNSUBSCRIBE news
PUNSUBSCRIBE退订模式订阅PUNSUBSCRIBE sensor.*
PUBSUB CHANNELS查看活跃频道列表PUBSUB CHANNELS "sensor.*"

操作示例

# 订阅者A(终端1)
127.0.0.1:6379> subscribe notifications
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "notifications"
3) (integer) 1# 订阅者B(终端2) 
127.0.0.1:6379> psubscribe system.*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "system.*"
3) (integer) 1# 发布消息(终端3)
127.0.0.1:6379> publish notifications "Service will be upgraded soon"
(integer) 1127.0.0.1:6379> publish system.alert "CPU usage exceeds 90%"
(integer) 1# 订阅者A收到:
1) "message"
2) "notifications"
3) "Service will be upgraded soon"# 订阅者B收到: 
1) "pmessage"
2) "system.*"
3) "system.alert"
4) "CPU usage exceeds 90%"

发布订阅的使用场景与优缺点

适用场景

  1. 实时通知系统:用户在线状态更新,即时聊天消息推送

  2. 事件驱动架构缓存失效广播,分布式配置更新

  3. 轻量级监控:服务器状态报警,业务指标异常通知

优点

  • 极低延迟(平均<1ms)

  • 支持百万级TPS消息吞吐

  • 模式匹配订阅实现灵活路由

  • 零外部依赖(仅需Redis服务)

缺点

消息不可靠性:不保证送达,离线订阅者会丢失消息

无持久化机制:重启后所有订阅关系丢失

客户端阻塞:订阅操作会占用连接线程(需异步处理)

替代方案建议:需要可靠消息时,使用Redis Streams(支持消息持久化、消费者组)或RabbitMQ/Kafka

在Java中使用RedisTemplate实现

配置RedisTemplate

package com.morris.redis.demo.pubsub;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** 对redis的键值进行序列化*/
@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(factory);// 使用 String 序列化 keytemplate.setKeySerializer(new StringRedisSerializer());// 使用 JSON 序列化 value(需要额外依赖 jackson)template.setValueSerializer(new GenericJackson2JsonRedisSerializer());// 对于 Hash 结构同理template.setHashKeySerializer(new StringRedisSerializer());template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());return template;}
}

实现消息发布者

package com.morris.redis.demo.pubsub;import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;import javax.annotation.Resource;/*** 消息发布者*/
@Service
public class MessagePublisher {@Resourceprivate RedisTemplate<String, Object> redisTemplate;public void sendNotification(String channel, String message) {redisTemplate.convertAndSend(channel, message);}
}

实现消息订阅者

package com.morris.redis.demo.pubsub;import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;import javax.annotation.Resource;/*** 消息订阅者*/
@Component
public class MessageSubscriber implements MessageListener {@Resourceprivate RedisTemplate redisTemplate;@Overridepublic void onMessage(Message message, byte[] pattern) {String channel = new String(message.getChannel());String body = (String) redisTemplate.getValueSerializer().deserialize(message.getBody());System.out.printf("收到频道[%s]的消息: %s\n", channel, body);}
}

配置订阅监听

package com.morris.redis.demo.pubsub;import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;/*** 配置redis消息订阅监听器*/
@Configuration
@Slf4j
public class RedisPubSubConfig {@Beanpublic RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory factory, MessageSubscriber messageSubscriber) {RedisMessageListenerContainer container = new RedisMessageListenerContainer();container.setConnectionFactory(factory);// 订阅具体频道container.addMessageListener(messageSubscriber, new ChannelTopic("notifications"));// 订阅模式匹配container.addMessageListener(messageSubscriber, new PatternTopic("system.*"));// 异常处理container.setErrorHandler((e) -> {log.error("[listen message] error ", e);});return container;}
}

使用示例

package com.morris.redis.demo.pubsub;import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;/*** 使用接口发布消息*/
@RestController
@RequestMapping("/pubsub")
public class PubSubDemoController {@Resourceprivate MessagePublisher publisher;// 发布告警@GetMapping("/alert")public String sendAlert(@RequestParam String message) {publisher.sendNotification("system.alert", message);return "警报已发送";}// 发布通知@GetMapping("/notify")public String sendNotify(@RequestParam String message) {publisher.sendNotification("notifications", message);return "通知已发送";}
}

http://www.ppmy.cn/embedded/172743.html

相关文章

DeepSeek进阶应用(一):结合Mermaid绘图(流程图、时序图、类图、状态图、甘特图、饼图)

&#x1f31f;前言: 在软件开发、项目管理和系统设计等领域&#xff0c;图表是表达复杂信息的有效工具。随着AI助手如DeepSeek的普及&#xff0c;我们现在可以更轻松地创建各种专业图表。 名人说&#xff1a;博观而约取&#xff0c;厚积而薄发。——苏轼《稼说送张琥》 创作者&…

探索DB-GPT:革新数据库交互的AI原生框架

引言 在AI与数据技术快速发展的今天,如何让自然语言与数据库实现无缝交互成为开发者关注的重点。DB-GPT作为一个开源的AI原生数据应用开发框架,通过整合大语言模型(LLM)、多代理协作、检索增强生成(RAG)等前沿技术,为开发者提供了高效构建数据驱动型AI应用的解决方案。…

PowerMock的使用

1. mock私有方法 待测试类 public class Demo {public void publicMethod() {System.out.println("public method invoke");protectedMethod("str");privateMethodA();privateMethodB();System.out.println("public method end");}protected v…

基于RTTR在C++中实现结构体数据的多层级动态读写

文章目录 1.背景2.RTTR2.1.注册结构体2.2.实现读操作2.3.实现写操作 3.读写调用例程4.结语 1.背景 目前有个项目&#xff0c;同一台电脑上的codesys程序将其结构体数据通过共享内存的方式写道了一个“共享内存”上。 我在取得内存数据后&#xff0c;需要对这个数据进行结构体的…

第13章贪心算法

贪心算法 局部最优求得总体最优 适用于桌上有6张纸币&#xff0c;面额为100 100 50 50 50 10&#xff0c;问怎么能拿走3张纸币&#xff0c;总面额最大&#xff1f;—拿单位价值最高的 只关注局部最优----关注拿一张的最大值拆解-----拿三次最大的纸币 不适用于桌面三件物品&am…

Linux常用命令速查手册

Linux常用命令速查手册 Linux常用命令速查手册1. 文件和目录操作1.1 查看当前目录&#xff08;pwd&#xff09;1.2 切换目录&#xff08;cd&#xff09;1.3 列出目录内容&#xff08;ls&#xff09;1.4 创建目录&#xff08;mkdir&#xff09;1.5 删除文件和目录&#xff08;rm…

xlua 运行原理

iOS限制App的二进制代码要一次性的包含在App内&#xff0c;也就是AOT&#xff0c;不支持JITLua代码作为资源文件&#xff0c;玩家下载&#xff0c;不涉及字节码&#xff0c;所以可以做热更Lua代码通过Lua虚拟机解释执行&#xff08;解释成机器码&#xff09;&#xff0c;并在虚…

小语言模型(SLM)技术解析:如何在有限资源下实现高效AI推理

引言&#xff1a;为什么小语言模型&#xff08;SLM&#xff09;是2025年的技术焦点&#xff1f; 2025年&#xff0c;人工智能领域正经历一场“由大变小”的革命。尽管大语言模型&#xff08;LLM&#xff09;如GPT-4、Gemini Ultra等在复杂任务中表现惊艳&#xff0c;但其高昂的…