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

相关推荐
S***26752 小时前
基于SpringBoot和Leaflet的行政区划地图掩膜效果实战
java·spring boot·后端
JIngJaneIL3 小时前
社区互助|社区交易|基于springboot+vue的社区互助交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·社区互助
这是程序猿4 小时前
基于java的ssm框架旅游在线平台
java·开发语言·spring boot·spring·旅游·旅游在线平台
i***t9194 小时前
基于SpringBoot和PostGIS的云南与缅甸的千里边境线实战
java·spring boot·spring
k***08294 小时前
【监控】spring actuator源码速读
java·spring boot·spring
一 乐4 小时前
应急知识学习|基于springboot+vue的应急知识学习系统(源码+数据库+文档)
数据库·vue.js·spring boot
vx_dmxq2114 小时前
【PHP考研互助系统】(免费领源码+演示录像)|可做计算机毕设Java、Python、PHP、小程序APP、C#、爬虫大数据、单片机、文案
java·spring boot·mysql·考研·微信小程序·小程序·php
5***g2985 小时前
新手如何快速搭建一个Springboot项目
java·spring boot·后端
kong79069285 小时前
微服务项目开发环境
微服务·nacos·rabbitmq·开发环境
Bug快跑-16 小时前
面向数据密集型应用的Python工程化实践与性能优化策略深度分析与经验分享探索研究篇
rabbitmq