Spring AMQP 项目将核心 Spring 概念应用于基于 AMQP 的消息传递解决方案的开发。它提供了一个“模板”作为发送和接收消息的高级抽象。它还通过“侦听器容器”为消息驱动的 POJO 提供支持。这些库促进了 AMQP 资源的管理,同时促进了依赖注入和声明性配置的使用。在所有这些情况下,您将看到与 Spring 框架中 JMS 支持的相似之处。
该项目由两部分组成;spring-amqp 是基础抽象,spring-rabbit 是 RabbitMQ 实现。
特征
-
用于异步处理入站消息的侦听器容器
-
RabbitTemplate 用于发送和接收消息
-
RabbitAdmin 用于自动声明队列、交换和绑定
案例
用于异步处理入站消息的侦听器容器
RabbitTemplate 用于发送和接收消息
RabbitAdmin 用于自动声明队列、交换和绑定
流程如下:
1. 在父工程中引入 spring- amqp 的依赖;
org.springframework.boot
spring-boot-starter-amqp
spring:
rabbitmq:
host:
port: 5672
virtual-host: /
username:
password:
2.在publisher服务中利用RabbitTemplate发送消息到simple.queue这个队列;
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void testSimpleQueue() {
String queueName = "simple.queue";
String message = "hello,Spring AMQP";
rabbitTemplate.convertAndSend(queueName,message);
}
3.在consumer服务中配置rabbitmq,编写消费逻辑,绑定simple.queue这个队列;
spring:
rabbitmq:
host:
port: 5672
virtual-host: /
username:
password:
@Component
public class listener {
@RabbitListener(queues = "simple.queue")
public void listenSimpleQueueMessage(String msg)throws InterruptedException {
System.out.println("Spring 消费者接收到的消息:{"+ msg + "}");
}
}
work Queue工作队列:实现一个队列绑定多个消费者
@RabbitListener(queues = "simple.queue")
public void listenWorkQueue2Message(String msg)throws InterruptedException {
System.err.println("Spring 消费者---2---接收到的消息:{"+ msg + "}"+ LocalTime.now());
Thread.sleep(200);
}
spring:
rabbitmq:
host: 192.168.211.128
port: 5672
virtual-host: /
username: itcast
password: 123321
listener:
simple:
prefetch: 1 #每次只能获取一条消息,处理完才能获取下一条消息



