背景
实际项目中遇到针对不同类型的消息,发送消息到不同的队列,而且队列可能还不存在,需要动态创建,于是写了如下代码,实践发现没啥问题,这里分享下。
环境
springboot 3.2
JDK 17
rabbitMQ模型介绍
图片来自参考链接表中的一篇介绍
注意,下面例子用到的是Direct模型
依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
配置
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
关键代码
@Resourceprivate ConnectionFactory connectionFactory;//这里指定一个exchange,之后会根据routeKey动态绑定不同的队列@Value("${rabbitmq.msgExchangeName:MsgExchange}")private String registerExchangeName;@Testvoid contextLoads() {}@Testvoid testMQ(){try (Connection connection = connectionFactory.createConnection();Channel channel = connection.createChannel(false)) {String msgType = "bus_error";// Declare an exchangeString exchangeName = registerExchangeName;channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, true);// Generate a unique queue nameString queueName = "msg_" + msgType;channel.queueDeclare(queueName, true, false, false, null);// Define the routing keychannel.queueBind(queueName, exchangeName, msgType);// Send a message to the exchangeString message = "Hello, RabbitMQ!";channel.basicPublish(exchangeName, msgType, null, message.getBytes());} catch (IOException | TimeoutException e) {e.printStackTrace();}}
至于监听队列,消费,就没啥好写的了,百度一大堆。
参考文档列表
RabbitMQ 5中消息模型介绍
RabbitMQ动态创建消息队列
RabbitMQ官方说明文档java指南