在Spring Boot中集成消息隊列通常使用Spring的Messaging模塊和相關的庫。常見的消息隊列有RabbitMQ、Kafka、ActiveMQ等。
下面以集成RabbitMQ為例來介紹如何在Spring Boot中集成消息隊列:
pom.xml
中添加RabbitMQ的依賴:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
application.properties
或application.yml
中配置RabbitMQ的連接信息:spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
RabbitTemplate
發送消息到RabbitMQ。import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MessageProducer {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendMessage(String message) {
rabbitTemplate.convertAndSend("exchangeName", "routingKey", message);
}
}
@RabbitListener
注解監聽RabbitMQ消息隊列。import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class MessageConsumer {
@RabbitListener(queues = "queueName")
public void handleMessage(String message) {
System.out.println("Received message: " + message);
}
}
sendMessage
方法,消息消費者會監聽queueName
隊列并處理接收到的消息。這樣就完成了在Spring Boot中集成RabbitMQ消息隊列。其他消息隊列的集成方式類似,只需要替換對應的依賴和配置信息即可。