当前位置: 首页 > news >正文

springboot 整合Redis实现发布/订阅功能

Redis发布/订阅模式简介

  1. 什么是发布/订阅?

    发布/订阅是一种消息通信模式,其中发送者(发布者)发布消息,多个接收者(订阅者)订阅并接收消息。发布者和订阅者之间没有直接联系,消息由消息中间件(如Redis)传递。

    在这里插入图片描述

  2. Redis 发布/定义的优点

    • 高性能:Redis作为内存存储,具备极高的读写性能,能够快速处理发布和订阅消息
    • 简单易用:Redis的发布/订阅接口简单,易于集成和使用
    • 实时性强:发布的消息会立即传递给所有订阅者,具备高实时性
  3. Redis发布/订阅的缺点

    • 消息丢失:由于Redis是内存存储,如果Redis实例宕机,未处理的消息可能会丢失
    • 无法持久化:Redis的发布/订阅模式不支持消息持久化,无法存储和检索历史消息
    • 订阅者不可控:发布者无法控制订阅者的数量和状态,无法保证所有订阅者都能收到消息
    • 无确认机制:发布者无法确认消息是否被订阅者接收和处理

    正如上述中Redis的缺点,Redis 的发布订阅功能并不可靠,如果我们需要保证消息的可靠性、包括确认、重试等要求,我们还是要选择MQ实现发布订阅

    Redis的发布/订阅应用场景:

    对于消息处理可靠性要求不强
    消息无需持久化
    消费能力无需通过增加消费方进行增强
    架构简单 中小型系统不希望应用过多中间件

  4. redis 发布订阅命令

    命令 描述
    Redis Unsubscribe 命令 指退订给定的频道
    Redis Subscribe 命令 订阅给定的一个或多个频道的信息
    Redis Pubsub 命令 查看订阅与发布系统状态
    Redis Punsubscribe 命令 退订所有给定模式的频道
    Redis Publish 命令 将信息发送到指定的频道
    Redis Psubscribe 命令 订阅一个或多个符合给定模式的频道

演示

  1. 添加依赖

    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional>
    </dependency>
    
  2. 配置Redis

    spring:#redisredis:# 地址host: 127.0.0.1# 端口,默认为6379port: 6379# 数据库索引database: 0# 密码password:# 连接超时时间timeout: 10slettuce:pool:# 连接池中的最小空闲连接min-idle: 5# 连接池中的最大空闲连接max-idle: 8# 连接池的最大数据库连接数max-active: 20# #连接池最大阻塞等待时间(使用负值表示没有限制)max-wait: -1ms
    
  3. 创建Redis配置类

    package com.example.demo.config;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.PatternTopic;
    import org.springframework.data.redis.listener.RedisMessageListenerContainer;
    import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;@Configuration
    public class RedisConfig {@BeanRedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,MessageListenerAdapter listenerAdapter) {//设置连接工厂RedisConnectionFactoryRedisMessageListenerContainer container = new RedisMessageListenerContainer();container.setConnectionFactory(connectionFactory);// 订阅订阅名称 micro 的通道container.addMessageListener(listenerAdapter, new ChannelTopic("micro"));// 订阅名称 'test-' 开头的全部通道container.addMessageListener(listenerAdapter, new PatternTopic("test-*"));return container;}@Beanpublic MessageListenerAdapter listenerAdapter(MessageReceiver receiver) {return new MessageListenerAdapter(receiver);}
    }
    
  4. 创建消息接收/发布类

    创建一个消息发布类,用于发布消息

    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.stereotype.Component;@Component
    public class MessagePublisher {private final StringRedisTemplate redisTemplate;public MessagePublisher(StringRedisTemplate redisTemplate) {this.redisTemplate = redisTemplate;}public void publish(String channel, String message) {redisTemplate.convertAndSend(channel, message);}
    }
    

    创建一个消息接收类,用于处理接收到的消息

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.data.redis.connection.Message;
    import org.springframework.data.redis.connection.MessageListener;
    import org.springframework.stereotype.Component;@Component
    @Slf4j
    public class MessageReceiver implements MessageListener {@Overridepublic void onMessage(Message message, byte[] pattern) {//消息通道String channel = new String(message.getChannel());//消息内容String messageBody = new String(message.getBody());// 消息订阅的匹配规则,如 new PatternTopic("test-*") 中的 test-*String msgPattern = new String(pattern);log.info("接收消息: channel={} body={} pattern={} ", channel, messageBody, msgPattern);// 这里处理接收的消息}
    }
    
  5. 编写controller测试

    创建一个简单的控制,来测试发布订阅功能

    import org.springframework.beans.factory.annotation.Autowired;
    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;@RestController
    @RequestMapping("/api")
    public class PublisherController {@Autowiredprivate MessagePublisher messagePublisher;@GetMapping("/publish")public String publish(@RequestParam String message) {messagePublisher.publish("micro", message);return "Message published: " + message;}
    }
    

通过本文,我们详细介绍了如何在 Spring Boot 中整合 Redis 实现发布/订阅功能,并提供了详细的代码示例。Redis 发布/订阅模式以其高性能和简单易用的特点,在实时消息传递场景中有着广泛的应用,但同时就如文中提到的小伙伴们也需要注意其消息丢失和无法持久化等缺点,需要根据实际业务需求选择。

http://www.hskmm.com/?act=detail&tid=13807

相关文章:

  • CCPC online 2025题解 ( A~H+K)
  • 2025.9.22总结 - A
  • 实用指南:GESP三级考纲+三级考试知识点详解
  • github操作备忘录
  • 9.22每日总结
  • 算法人生
  • 动态规划专题
  • 【51单片机】【protues仿真】基于51单片机PM2.5温湿度测量蓝牙架构
  • 每日反思(2025.9.22)
  • 洛谷题单指南-进阶数论-P4942 小凯的数字
  • 【炼石计划NOIP】第八套 赛后总结
  • 下载了idea
  • vite7-webos网页版os管理|Vue3+Vite7+ArcoDesign搭建pc端os后台系统
  • 三门问题的多种解法,总有一个你看得懂
  • hbase学习——创建springboot+hbase项目
  • python_Day22笔记
  • .NET周刊【9月第1期 2025-09-07】
  • SUDO提权
  • 2025.9.19 总结
  • 2025.9.18 总结
  • 越南文识别技术:将纸质文档和信息快速、准确地转化为可编辑、可检索的数字数据
  • 23
  • 9.22日总结
  • 9.16 总结
  • Halcon抛出异常日志
  • [PaperReading] Mind Search: Mimicking Human Minds Elicits Deep AI Searcher
  • 穷举法(c语言版)
  • ZYNQ PS 端 UART 接收数据素材帧(初学者友好版)嵌入式编程 C语言 c++ 软件开发
  • 详细介绍:深入理解Kafka事务
  • 能碳园区 / 工厂系统 - 智慧园区