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

相关推荐
啊啊啊迈 旋棍18 分钟前
生态整合与实战篇:Spring Boot 整合 RocketMQ 完全指南
spring boot·rocketmq·java-rocketmq
减瓦1 小时前
Jackson 使用指南
java·spring boot·json
旺仔学长 哈哈2 小时前
基于SpringBoot的在线招聘测评系统的设计与实现----附源码35253+数据库文档
数据库·spring boot·后端·在线招聘
万亿少女的梦1682 小时前
基于Spring Boot的乐助在线助农系统设计与实现
java·spring boot·mysql·敏感词过滤·助农系统
码农学院13 小时前
基于Spring Boot的跨境电商多语言订单管理系统架构设计
java·大数据·spring boot
whyfail19 小时前
前端学 Spring Boot(5):从“你是谁”到“服务真的上线了”
前端·spring boot·后端
2601_9538246119 小时前
【计算机毕业设计】基于Spring Boot的画师接稿平台设计与实现
java·spring boot·后端
稚南城才子,乌衣巷风流21 小时前
Spring Boot 中的 @Lazy 注解:延迟加载的深入解析与实践
java·spring boot·后端
hexu_blog1 天前
springboot3集成shardingsphere4.0 分表分库
java·spring boot·mybatis
乐观的Terry1 天前
9、发布系统-Webhook自动发布
java·spring boot·spring·spring cloud·mybatis