✅P294_商城业务-订单服务-创建业务交换机-队列
大约 2 分钟
库存服务导入RabbitMQ依赖
cfmall-ware/pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
RabbitMQ配置
cfmall-ware/src/main/resources/application.yml
spring:
rabbitmq:
addresses: 192.168.56.10
virtual-host: /
RabbitMQ序列化配置
cfmall-ware/src/main/java/com/gyz/cfmall/ware/config/MyRabbitMQConfig.java
@Bean
public AbstractMessageConverter messageConverter() {
return new Jackson2JsonMessageConverter();
}
开启RabbitMQ
CfmallWareApplication启动类上添加@EnableRabbit注解
创建交换机、队列、绑定关系
参考下图涉及库存服务的交换机和队列进行创建:
cfmall-ware/src/main/java/com/gyz/cfmall/ware/config/MyRabbitMQConfig.java
如果不添加监听队列部分代码,则创建交换机、队列、绑定关系失败;
问题原因:只有当第一次连接上RabbitMQ时,无交换机、队列、绑定关系才会创建
解决方案:添加监听队列,代码如下:
@RabbitListener(queues = "stock.release.stock.queue")
public void handle(Message message) {
}
注意:交换机、队列、绑定关系创建成功后,将监听队列注释
完整代码如下:
package com.gyz.cfmall.ware.config;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.AbstractMessageConverter;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
/**
* @author: gongyuzhuo
* @since: 2024-02-06 16:15
* @description: RabbitMQ的序列化
*/
@Configuration
public class MyRabbitMQConfig {
/**
* 启动库存服务后,发现并没有创建交换机、队列、绑定关系
* 问题原因:只有当第一次连接上RabbitMQ时,无交换机、队列、绑定关系才会创建
* 解决方案:监听队列
* @param message
*/
@RabbitListener(queues = "stock.release.stock.queue")
public void handle(Message message) {
}
@Bean
public AbstractMessageConverter messageConverter() {
return new Jackson2JsonMessageConverter();
}
@Bean
public Exchange stockEventExchange() {
return new TopicExchange("stock-event-exchange", true, false);
}
@Bean
public Queue stockReleaseStockQueue() {
return new Queue("stock.release.stock.queue", true, false, false, null);
}
@Bean
public Queue stockDelayQueue() {
Map<String, Object> arguments = new HashMap<>();
arguments.put("x-dead-letter-exchange", "stock-event-exchange");
arguments.put("x-dead-letter-routing-key", "stock.release");
arguments.put("x-message-ttl", 120000);
return new Queue("stock.delay.queue", true, false, false, arguments);
}
@Bean
public Binding stockReleaseBinding() {
return new Binding("stock.release.stock.queue",
Binding.DestinationType.QUEUE, "stock-event-exchange", "stock.release.#", null);
}
@Bean
public Binding stockLockedBinding() {
return new Binding("stock.delay.queue", Binding.DestinationType.QUEUE,
"stock-event-exchange", "stock.locked", null);
}
}