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

相关推荐
过期动态12 小时前
【LeetCode 热题 100】移动零
java·数据结构·算法·leetcode·职场和发展·rabbitmq
苏渡苇12 小时前
服务容错的必要性与Spring Cloud Alibaba Sentinel 限流配置实战
spring boot·spring cloud·sentinel
bug菌12 小时前
【SpringBoot 3.x 第254节】夯爆了,数据库访问性能优化实战详解!
数据库·spring boot·后端
不肯过江东丶13 小时前
大聪明教你学Java | Spring AI Lab:一个让你 3 分钟接入 AI 对话能力的 Spring Boot 工具箱
spring boot·后端
lulu121654407814 小时前
Claude Code SpringBoot技能体系架构设计与演进
java·人工智能·spring boot·后端·ai编程
callJJ14 小时前
Nacos 详解——从概念到实战
java·spring boot·spring·spring cloud·微服务·nacos
Simon5231415 小时前
反射------5.26学习小计
java·开发语言·spring boot
study-Java16 小时前
校园失物招领平台
java·spring boot·vue·intellij-idea·visual studio code
暗冰ཏོ19 小时前
springboot_从入门到高级详细讲解
java·spring boot·后端·spring·maven
Mr-Wanter19 小时前
Spring Boot 2 升级到 Spring Boot 3 后 Nacos 热更新失效问题分析
java·spring boot·spring