spring提供了spring-amqp,具体操作可参考:
以下示例均基于MAVEN.
与springBoot整合
导入pom依赖
Prerequisites: install and run the RabbitMQ broker (http://www.rabbitmq.com/download.html). Then grab the spring-rabbit JAR and all its dependencies - the easiest way to do that is to declare a dependency in your build tool, e.g. for Maven:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
在resources新建下新建rabbit-context.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit" xsi:schemaLocation="http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <rabbit:connection-factory id="connectionFactory" addresses="172.30.1.45:5672,172.30.1.46:5672" username="ecas" password="ecas" virtual-host="ecas" channel-cache-size="50" /> <bean name="aaaListener" class="com.rabbitmq.service.service"></bean> <rabbit:template id="amqpTemplate" connection-factory="connectionFactory" /> </beans>
在程序入口,也就是你的Application.java需要加入这样一条注释
@ImportResource("classpath:rabbit-context.xml")
消费者
这里示例最简单的实现.如果你想实现更多,请参考https://docs.spring.io/spring-amqp/docs/2.0.3.BUILD-SNAPSHOT/reference/html/_reference.html#_introduction_8
The easiest way to receive a message asynchronously is to use the annotated listener endpoint infrastructure. In a nutshell, it allows you to expose a method of a managed bean as a Rabbit listener endpoint.
异步接收消息最简单的方法是使用带注释的侦听器端点基础设施。简单地说,它允许您将托管bean的方法公开为一个rabbit侦听器端点。
监听单个Queue
eg:
@Component public class MyService { @RabbitListener(queues = "myQueue") public void processOrder(String data) { ... } }
每当一条消息在名为myQueue的队列上可用时,processOrder方法就会相应地被调用(在本例中为消息的有效负载)。
带注释的端点基础架构为每个带注释的方法在后台创建一个消息侦听器容器,使用
RabbitListenerContainerFactory
在这个例子中
myQueue
必须已经存在并且被绑定到一些交换。只要RabbitAdmin
存在于应用程序上下文中,就可以自动声明和绑定队列。
When using the
queues
attribute, you can specify that the associated container can listen to multiple queues. You can use a@Header
annotation to make the queue name from which a message was received available to the POJO method:使用该
queues
属性时,可以指定关联的容器可以侦听多个队列。您可以使用@Header
注释来将接收到消息的队列名称用于POJO方法
监听多个Queue
eg:
@Component public class MyService { @RabbitListener(queues = { "queue1", "queue2" } ) public void processOrder(String data, @Header(AmqpHeaders.CONSUMER_QUEUE) String queue) { ... } }
如果你想知道监听到哪个消息队列的消息,你可以使用@Header
注释
eg:
@RabbitListener(queues = { "aaa", "bbb" }) public void processMessage(String data, @Header(AmqpHeaders.CONSUMER_QUEUE) String queue) { System.out.println("我接收到来自'" + queue + "'的消息: " + data); }
与Spring整合同上,不过要在你的web.xml中声明RabbitMQ.xml
更多详细信息请参考 https://docs.spring.io/spring-amqp/reference/html/index.html