Spring Boot整合RabbitMQ可以使用Spring AMQP项目,以下是使用Spring Boot整合RabbitMQ的基本步骤,包括不同的工作模式和交换机类型的代码示例。
- 添加依赖到
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
- 配置RabbitMQ连接在
application.properties
:
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
简单模式(Simple):
@Component
public class SimpleSender {
@Autowired
private AmqpTemplate amqpTemplate;
public void send(String message) {
amqpTemplate.convertAndSend("queueName", message);
}
}
@Component
public class SimpleReceiver {
@RabbitListener(queues = "queueName")
public void receive(String message) {
System.out.println("Received <" + message + ">");
}
}
工作队列模式(Work Queue):
@Component
public class WorkQueueSender {
@Autowired
private AmqpTemplate amqpTemplate;
public void send(String message) {
amqpTemplate.convertAndSend("workQueue", message);
}
}
@Component
public class WorkQueueReceiver {
@RabbitListener(queues = "workQueue")
public void receive(String message) {
System.out.println("Received <" + message + ">");
}
}
发布/订阅模式(Publish/Subscribe):
@Component
public class PublishSubscribeSender {
@Autowired
private AmqpTemplate amqpTemplate;
public void send(String message) {
amqpTemplate.convertAndSend("exchangeName", "routingKey", message);
}
}
@Component
public class PublishSubscribeReceiver {
@RabbitListener(queues = "queueName")
public void receive(String message) {
System.out.println("Received <" + message + ">");
}
}
路由模式(Routing):
@Component
public class RoutingSender {
@Autowired
private AmqpTemplate amqpTemplate;
public void send(String message) {
amqpTemplate.convertAndSend("exchangeName", "routingKey", message);
}
}
@Component
public class RoutingReceiver {
@RabbitListener(bindings = @QueueBinding(
value = @Queue,
exchange = @Exchange(value = "exchangeName", type