Spring Boot提供了RabbitMQ的自动化配置,使得整合RabbitMQ变得非常容易。
首先,需要在pom.xml文件中引入amqp-client和spring-boot-starter-amqp依赖:
xml
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
接下来需要在application.properties文件中配置RabbitMQ连接信息:
properties
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/
然后编写消息发送者:
java
@Component
public class RabbitMQSender {
private final RabbitTemplate rabbitTemplate;
public RabbitMQSender(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
public void send(String message) {
rabbitTemplate.convertAndSend("my-exchange", "my-routing-key", message);
}
}
其中,my-exchange和my-routing-key是需要自己定义的交换机和路由键。
最后编写消息消费者:
java
@Component
public class RabbitMQReceiver {
@RabbitListener(queues = "my-queue")
public void receive(String message) {
System.out.println("Received message: " + message);
}
}
其中,my-queue也是需要自己定义的队列。
在以上步骤完成后,即可实现消息的发送和消费。