- 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编码的方式:
publicstaticvoid main(finalString... args)throwsException{
ConnectionFactory cf =newCachingConnectionFactory();
// set up the queue, exchange, binding on the broker
RabbitAdmin admin =newRabbitAdmin(cf);
Queue queue =newQueue("myQueue");
admin.declareQueue(queue);
TopicExchange exchange =newTopicExchange("myExchange");
admin.declareExchange(exchange);
admin.declareBinding(
BindingBuilder.bind(queue).to(exchange).with("foo.*"));
// set up the listener and container
SimpleMessageListenerContainer container =
newSimpleMessageListenerContainer(cf);
Object listener =newObject(){
publicvoid handleMessage(String foo){
System.out.println(foo);
}
};
MessageListenerAdapter adapter =newMessageListenerAdapter(listener);
container.setMessageListener(adapter);
container.setQueueNames("myQueue");
container.start();
// send something
RabbitTemplate template =newRabbitTemplate(cf);
template.convertAndSend("myExchange","foo.bar","Hello, world!");
Thread.sleep(1000);
container.stop();
}
使用Spring的方式:
publicstaticvoid main(finalString... args)throwsException{
AbstractApplicationContext ctx =
newClassPathXmlApplicationContext("context.xml");
RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
template.convertAndSend("Hello, world!");
Thread.sleep(1000);
ctx.destroy();
}
publicclassFoo{
publicvoid listen(String foo){
System.out.println(foo);
}
}
<!--context.xml -->
<rabbit:connection-factoryid="connectionFactory"/>
<rabbit:templateid="amqpTemplate"connection-factory="connectionFactory"
exchange="myExchange"routing-key="foo.bar"/>
<rabbit:adminconnection-factory="connectionFactory"/>
<rabbit:queuename="myQueue"/>
<rabbit:topic-exchangename="myExchange">
<rabbit:bindings>
<rabbit:bindingqueue="myQueue"pattern="foo.*"/>
</rabbit:bindings>
</rabbit:topic-exchange>
<rabbit:listener-containerconnection-factory="connectionFactory">
<rabbit:listenerref="foo"method="listen"queue-names="myQueue"/>
</rabbit:listener-container>
<beanid="foo"class="foo.Foo"/>