springboot 3.x 之 集成rabbitmq实现动态发送消息给不同的队列

背景

实际项目中遇到针对不同类型的消息,发送消息到不同的队列,而且队列可能还不存在,需要动态创建,于是写了如下代码,实践发现没啥问题,这里分享下。

环境

springboot 3.2

JDK 17

rabbitMQ模型介绍


图片来自参考链接表中的一篇介绍

注意,下面例子用到的是Direct模型

依赖

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

配置

xml 复制代码
spring.rabbitmq.host=xxx
spring.rabbitmq.port=5672
spring.rabbitmq.username=xxx
spring.rabbitmq.password=xxx
spring.rabbitmq.virtual-host=/
#开启发布确认回调
spring.rabbitmq.publisher-confirm-type=correlated
spring.rabbitmq.publisher-returns=true
spring.rabbitmq.listener.simple.retry.enabled=true
spring.rabbitmq.listener.simple.retry.max-attempts=3
spring.rabbitmq.listener.simple.retry.initial-interval=10000ms

关键代码

java 复制代码
    @Resource
    private ConnectionFactory connectionFactory;
    //这里指定一个exchange,之后会根据routeKey动态绑定不同的队列
    @Value("${rabbitmq.msgExchangeName:MsgExchange}")
    private String registerExchangeName;

    @Test
    void contextLoads() {
    }

    @Test
    void testMQ(){
        try (Connection connection = connectionFactory.createConnection();
             Channel channel = connection.createChannel(false)) {
            String msgType = "bus_error";
            // Declare an exchange
            String exchangeName = registerExchangeName;
            channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, true);
            // Generate a unique queue name
            String queueName = "msg_" + msgType;
            channel.queueDeclare(queueName, true, false, false, null);
            // Define the routing key
            channel.queueBind(queueName, exchangeName, msgType);
            // Send a message to the exchange
            String message = "Hello, RabbitMQ!";
            channel.basicPublish(exchangeName, msgType, null, message.getBytes());
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }

至于监听队列,消费,就没啥好写的了,百度一大堆。

参考文档列表

RabbitMQ 5中消息模型介绍

RabbitMQ动态创建消息队列

RabbitMQ官方说明文档java指南

相关推荐
YUELEI1181 小时前
Springboot WebSocket
spring boot·后端·websocket
小蒜学长1 小时前
springboot基于JAVA的二手书籍交易系统的设计与实现(代码+数据库+LW)
java·数据库·spring boot·后端
全职计算机毕业设计2 小时前
基于SpringBoot框架的在线教育系统设计与实现(三套文档参考)
java·spring boot·后端
No8g攻城狮2 小时前
【异常解决】使用DateUtil.isSameDay()方法判断秒级时间戳是否属于同一天踩过的坑
java·jvm·spring boot·java-ee·springboot
努力也学不会java3 小时前
【Spring】Spring事务和事务传播机制
java·开发语言·人工智能·spring boot·后端·spring
IT·陈寒4 小时前
从 Spring 到 SpringBoot,再到 SpringAI:框架的进化与思考
java·spring boot·spring
张较瘦_4 小时前
Springboot | 初识Springboot 从“手动做饭”到“点外卖”的编程革命
java·spring boot·后端
一个龙的传说5 小时前
springboot优雅停止的流程梳理
java·spring boot·rpc
摇滚侠5 小时前
Spring Boot 3零基础教程,WEB 开发 国际化 Spring Boot + Thymeleaf 笔记45
spring boot·笔记·后端
韩立学长6 小时前
【开题答辩实录分享】以《智能垃圾回收小程序》为例进行答辩实录分享
spring boot·小程序