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指南

相关推荐
Pniubi2 小时前
基于RabbitMQ实现延迟队列
rabbitmq
蜗牛8753 小时前
为 Spring Boot 团队做一个 Elasticsearch 查询工作台:六种模式、语义补全与浏览器直连
spring boot
养军博客5 小时前
Spring Boot 3.x + Spring Security 6.x 整合 JWT 实战:jjwt 与 java-jwt 两种工具库详解
java·spring boot·springsecurity
txxzjmzlh17 小时前
SpringBoot 统⼀功能处理
java·spring boot·后端
秋天的怀念_David1 天前
算法一千零一夜 · 第二十六夜 协议的母语
java·spring boot·算法
余槐i1 天前
MySQL 8.0 联合索引走错:为什么加了索引查询反而从 200ms 变成 8s
java·spring boot·mysql·docker·性能优化
nice_lcj5201 天前
【从零理解 Spring AI · 03】Spring AI 在 Spring 生态里的位置
java·spring boot·大模型·spring ai·ai应用开发
AI源码2 天前
旅游推荐管理系统
spring boot
aiks_yuan2 天前
Spring Boot SSE 流式输出变成一次性返回怎么办:大模型打字机效果失效的 5 个原因(Spring Boot 4.1.2 实测)
spring boot
一条泥憨鱼2 天前
【消息队列】ACK确认了什么:消息队列可靠投递的完整链路
java·后端·kafka·消息队列·rabbitmq