- Spring AMQP项目介绍
Spring AMQP项目将Spring的核心思想应用于基于AMQP的消息解决方案的开发上。它提供了“template”这个高度抽象来发送和接收信息。它同样提供了消息驱动的实体,这些实体存在于“listener
container”容器中。这些库不但使得AMQP资源的管理变得容易,与此同时促进了依赖注入和声明式配置的使用。在所有的情况下,你将看到许多Spring框架提供的类似于JMS的便利。
这个项目包含两部分:
1、spring-amqp的基础抽象;
2、spring-rabbit这个RabbitMQ的实现
特点:
1、异步处理没有绑定消息的监听容器;
2、RabbitTemplate发送和接收消息;
3、RabbitAdmin自动声明队列,交换和绑定。
- Spring AMQP快速入门
推荐开始在你的项目中使用spring-amqp的快捷方式是使用依赖管理系统,例如Maven和Gradle,配置片段如下:
<dependencies>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
</dependencies>
使用Java编码的方式:
public static void main(final String... args) throws Exception {
ConnectionFactory cf = new CachingConnectionFactory();
// set up the queue, exchange, binding on the broker
RabbitAdmin admin = new RabbitAdmin(cf);
Queue queue = new Queue("myQueue");
admin.declareQueue(queue);
TopicExchange exchange = new TopicExchange("myExchange");
admin.declareExchange(exchange);
admin.declareBinding(
BindingBuilder.bind(queue).to(exchange).with("foo.*"));
// set up the listener and container
SimpleMessageListenerContainer container =
new SimpleMessageListenerContainer(cf);
Object listener = new Object() {
public void handleMessage(String foo) {
System.out.println(foo);
}
};
MessageListenerAdapter adapter = new MessageListenerAdapter(listener);
container.setMessageListener(adapter);
container.setQueueNames("myQueue");
container.start();
// send something
RabbitTemplate template = new RabbitTemplate(cf);
template.convertAndSend("myExchange", "foo.bar", "Hello, world!");
Thread.sleep(1000);
container.stop();
}
使用Spring的方式:
public static void main(final String... args) throws Exception {
AbstractApplicationContext ctx =
new ClassPathXmlApplicationContext("context.xml");
RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
template.convertAndSend("Hello, world!");
Thread.sleep(1000);
ctx.destroy();
}
public class Foo {
public void listen(String foo) {
System.out.println(foo);
}
}
<!--context.xml -->
<rabbit:connection-factory id="connectionFactory" />
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory"
exchange="myExchange" routing-key="foo.bar"/>
<rabbit:admin connection-factory="connectionFactory" />
<rabbit:queue name="myQueue" />
<rabbit:topic-exchange name="myExchange">
<rabbit:bindings>
<rabbit:binding queue="myQueue" pattern="foo.*" />
</rabbit:bindings>
</rabbit:topic-exchange>
<rabbit:listener-container connection-factory="connectionFactory">
<rabbit:listener ref="foo" method="listen" queue-names="myQueue" />
</rabbit:listener-container>
<bean id="foo" class="foo.Foo" />