Springboot2.X整合RabbitMQ
1.新建springboot工程并选择添加web组件
2.pom文件 配置
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.net.mqwithspboot</groupId>
<artifactId>rabbitmqdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>rabbitmqdemo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3.配置文件
spring:
rabbitmq:
host: 20.18.24.143
port: 5672
virtual-host: devTest
username: admin
password: 123456
4.RabbitMQConfig配置类
@Configuration
public class RabbitMQConfig {
public static final String EXXCHANGE_NAME = "order_exchange";
public static final String QUEUE = "order_queue";
/**
* 交换机
* @return
*/
@Bean
public Exchange orderExchange(){
return ExchangeBuilder.topicExchange(EXXCHANGE_NAME).durable(true).build();
}
/**
* 队列
* @return
*/
@Bean
public Queue orderQueue(){
return QueueBuilder.durable(QUEUE).build();
}
/**
* 交换机和队列绑定关系
*/
@Bean
public Binding orderBinding(Queue queue,Exchange exchange ){
return BindingBuilder.bind(queue).to(exchange).with("order.#").noargs();
}
}
5.消费者代码(一个监听指定队列的服务)
@Component
@RabbitListener(queues = "order_queue")
public class OrderMQListener {
@RabbitHandler
public void messageHandler(String body, Message message, Channel channel) throws IOException {
long msgTag = message.getMessageProperties().getDeliveryTag();
System.out.println("msgTag="+msgTag);
System.out.println("message="+message.toString());
System.out.println("body="+body);
}
}
6.生产者测试代码
@Test
void testSend() {
template.convertAndSend(RabbitMQConfig.EXXCHANGE_NAME,"order.new","新订单");
}