spring-amqp結合使用rabbitmq
Spring AMQP提供了org.springframework.amqp.core.AmqpTemplate來發送與接收消息。AMQP模板實現支持發送與接收POJOs而非javax.jms.Message實例。他們還提供了一種方式來自定義用于編排對象的MessageConverter。Spring 與JMS用戶會發現JmsTemplate與新的AmqpTemplate之間的相似性。
下面的代碼片段介紹了如何聯合使用Spring AMQP與RabbitMQ處理同步消息。RabbitMQ是VMware的產品,并且是官方Spring AMQP示例中所用的默認AMQP實現。
Maven項目添加依賴包spring-rabbit
<dependencies>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
</dependencies>just 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();
}</pre></div>
Or, the Spring way
1.applicationContext-amqp.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" /></pre></div>
2.Method Foo
public class Foo {
public void listen(String foo) {
System.out.println(foo);
}
}</pre></div>
3.Method Main
public static void main(final String... args) throws Exception {
AbstractApplicationContext ctx =
new ClassPathXmlApplicationContext("applicationContext-amqp.xml");
RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
template.convertAndSend("Hello, world!");
Thread.sleep(1000);
ctx.destroy();
}</pre></div>
</div>
來自:http://hunng.com/2014/07/15/spring-amqp/
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!
相關經驗
相關資訊