主题
Spring Boot使用RabbitMQ
在Spring Boot中集成RabbitMQ是一个常见的需求,主要用于实现消息队列和事件驱动的微服务架构。
步骤 1: 添加依赖
首先,你需要在你的pom.xml
或build.gradle
文件中添加RabbitMQ的依赖。对于Maven,添加以下依赖:
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
对于Gradle,添加:
groovy
implementation 'org.springframework.boot:spring-boot-starter-amqp'
步骤 2: 配置RabbitMQ
接下来,在application.properties
或application.yml
中配置RabbitMQ的连接信息:
properties
# application.properties
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
或者在application.yml
中:
yaml
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
步骤 3: 创建生产者
创建一个生产者类,用于发送消息到RabbitMQ:
java
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class RabbitMQProducer {
private final RabbitTemplate rabbitTemplate;
@Autowired
public RabbitMQProducer(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
public void sendMessage(String message, String exchange, String routingKey) {
rabbitTemplate.convertAndSend(exchange, routingKey, message);
System.out.println("Sent message = " + message);
}
}
步骤 4: 创建消费者
创建一个消费者类,用于接收来自RabbitMQ的消息:
java
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class RabbitMQConsumer {
@RabbitListener(queues = "${rabbitmq.queue}")
public void receiveMessage(String message) {
System.out.println("Received message = " + message);
}
}
注意:在application.properties
或application.yml
中定义rabbitmq.queue
属性。
步骤 5: 使用生产者和消费者
在你的业务逻辑中,你可以注入RabbitMQProducer
来发送消息,以及确保RabbitMQConsumer
被正确配置以接收消息。