http://blog.csdn.net/zhu_tianwei/article/details/40919031

实现使用Exchange类型为DirectExchange. routingkey的名称默认为Queue的名称。异步发送消息。

1.配置文件

  1. #============== rabbitmq config ====================
  2. rabbit.hosts=192.168.36.102
  3. rabbit.username=admin
  4. rabbit.password=admin
  5. rabbit.virtualHost=/
  6. rabbit.queue=spring-queue-async
  7. rabbit.routingKey=spring-queue-async#<span style="font-family: Helvetica, Tahoma, Arial, sans-serif; font-size: 14px; line-height: 25.2000007629395px;">routingkey的名称默认为Queue的名称</span>

2.生产者配置applicationContext-rabbitmq-async-send.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="
  6. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
  8. <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  9. <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
  10. <property name="ignoreResourceNotFound" value="true" />
  11. <property name="locations">
  12. <list>
  13. <!-- 标准配置 -->
  14. <value>classpath*:/application.properties</value>
  15. </list>
  16. </property>
  17. </bean>
  18. <!-- 创建connectionFactory -->
  19. <bean id="rabbitConnectionFactory"
  20. class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
  21. <constructor-arg value="${rabbit.hosts}"/>
  22. <property name="username" value="${rabbit.username}"/>
  23. <property name="password" value="${rabbit.password}"/>
  24. <property name="virtualHost" value="${rabbit.virtualHost}"/>
  25. <property name="channelCacheSize" value="5"/>
  26. </bean>
  27. <!-- 创建rabbitAdmin 代理类 -->
  28. <bean id="rabbitAdmin"
  29. class="org.springframework.amqp.rabbit.core.RabbitAdmin">
  30. <constructor-arg ref="rabbitConnectionFactory" />
  31. </bean>
  32. <!-- 创建rabbitTemplate 消息模板类
  33. -->
  34. <bean id="rabbitTemplate"
  35. class="org.springframework.amqp.rabbit.core.RabbitTemplate">
  36. <constructor-arg ref="rabbitConnectionFactory"></constructor-arg>
  37. <property name="routingKey" value="${rabbit.routingKey}"></property>
  38. </bean>
  39. </beans>

3.生产者发送消息代码Send.java

  1. package cn.slimsmart.rabbitmq.demo.spring.async;
  2. import org.springframework.amqp.core.AmqpTemplate;
  3. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;
  6. public class Send {
  7. public static void main(String[] args) throws InterruptedException {
  8. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-rabbitmq-async-send.xml");
  9. AmqpTemplate amqpTemplate = context.getBean(RabbitTemplate.class);
  10. for(int i=0;i<1000;i++){
  11. amqpTemplate.convertAndSend("test spring async=>"+i);
  12. Thread.sleep(3000);
  13. }
  14. }
  15. }

4.处理消息类ReceiveMsgHandler.Java

  1. package cn.slimsmart.rabbitmq.demo.spring.async;
  2. public class ReceiveMsgHandler {
  3. public void handleMessage(String text) {
  4. System.out.println("Received: " + text);
  5. }
  6. }

5.配置applicationContext-rabbitmq-async-receive.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="
  6. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
  8. <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  9. <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
  10. <property name="ignoreResourceNotFound" value="true" />
  11. <property name="locations">
  12. <list>
  13. <!-- 标准配置 -->
  14. <value>classpath*:/application.properties</value>
  15. </list>
  16. </property>
  17. </bean>
  18. <!-- 创建connectionFactory -->
  19. <bean id="rabbitConnectionFactory"
  20. class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
  21. <constructor-arg value="${rabbit.hosts}"/>
  22. <property name="username" value="${rabbit.username}"/>
  23. <property name="password" value="${rabbit.password}"/>
  24. <property name="virtualHost" value="${rabbit.virtualHost}"/>
  25. <property name="channelCacheSize" value="5"/>
  26. </bean>
  27. <!-- 声明消息转换器为SimpleMessageConverter -->
  28. <bean id="messageConverter"
  29. class="org.springframework.amqp.support.converter.SimpleMessageConverter">
  30. </bean>
  31. <!-- 监听生产者发送的消息开始 -->
  32. <!-- 用于接收消息的处理类 -->
  33. <bean id="receiveHandler"
  34. class="cn.slimsmart.rabbitmq.demo.spring.async.ReceiveMsgHandler">
  35. </bean>
  36. <!-- 用于消息的监听的代理类MessageListenerAdapter -->
  37. <bean id="receiveListenerAdapter"
  38. class="org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter">
  39. <constructor-arg ref="receiveHandler" />
  40. <property name="defaultListenerMethod" value="handleMessage"></property>
  41. <property name="messageConverter" ref="messageConverter"></property>
  42. </bean>
  43. <!-- 用于消息的监听的容器类SimpleMessageListenerContainer,对于queueName的值一定要与定义的Queue的值相同 -->
  44. <bean id="listenerContainer"
  45. class="org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer">
  46. <property name="queueNames" value="${rabbit.queue}"></property>
  47. <property name="connectionFactory" ref="rabbitConnectionFactory"></property>
  48. <property name="messageListener" ref="receiveListenerAdapter"></property>
  49. </bean>
  50. <!-- 监听生产者发送的消息结束 -->
  51. </beans>

5.接收消息启动类Receive.java

  1. package cn.slimsmart.rabbitmq.demo.spring.async;
  2. import org.springframework.context.support.ClassPathXmlApplicationContext;
  3. public class Receive {
  4. public static void main(String[] args) {
  5. new ClassPathXmlApplicationContext("applicationContext-rabbitmq-async-receive.xml");
  6. }
  7. }

启动接收消息,再发送消息

  1. Received: test spring async=>0
  2. Received: test spring async=>1
  3. Received: test spring async=>2
  4. Received: test spring async=>3
  5. Received: test spring async=>4
  6. Received: test spring async=>5
  7. Received: test spring async=>6
  8. Received: test spring async=>7
  9. ......

若报如下错误,说明消息队列不存在,请在控制台添加消息队列。

  1. log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
  2. log4j:WARN Please initialize the log4j system properly.
  3. Exception in thread "main" org.springframework.context.ApplicationContextException: Failed to start bean 'listenerContainer'; nested exception is org.springframework.amqp.AmqpIllegalStateException: Fatal exception on listener startup
  4. at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:170)
  5. at org.springframework.context.support.DefaultLifecycleProcessor.access$1(DefaultLifecycleProcessor.java:154)
  6. at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:339)
  7. at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:143)
  8. at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:108)
  9. at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:931)
  10. at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472)
  11. at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:73)
  12. at cn.slimsmart.rabbitmq.demo.spring.async.Consumer.main(Consumer.java:7)
  13. Caused by: org.springframework.amqp.AmqpIllegalStateException: Fatal exception on listener startup
  14. at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doStart(SimpleMessageListenerContainer.java:333)
  15. at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.start(AbstractMessageListenerContainer.java:360)
  16. at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:167)
  17. ... 8 more
  18. Caused by: org.springframework.amqp.rabbit.listener.FatalListenerStartupException: Cannot prepare queue for listener. Either the queue doesn't exist or the broker will not allow us to use it.
  19. at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.start(BlockingQueueConsumer.java:228)
  20. at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:516)
  21. at java.lang.Thread.run(Unknown Source)
  22. Caused by: java.io.IOException
  23. at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:106)
  24. at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:102)
  25. at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:124)
  26. at com.rabbitmq.client.impl.ChannelN.queueDeclarePassive(ChannelN.java:788)
  27. at com.rabbitmq.client.impl.ChannelN.queueDeclarePassive(ChannelN.java:61)
  28. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  29. at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
  30. at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  31. at java.lang.reflect.Method.invoke(Unknown Source)
  32. at org.springframework.amqp.rabbit.connection.CachingConnectionFactory$CachedChannelInvocationHandler.invoke(CachingConnectionFactory.java:348)
  33. at com.sun.proxy.$Proxy8.queueDeclarePassive(Unknown Source)
  34. at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.start(BlockingQueueConsumer.java:213)
  35. ... 2 more
  36. Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; reason: {#method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no queue 'spring-queue-async' in vhost '/', class-id=50, method-id=10), null, ""}
  37. at com.rabbitmq.utility.ValueOrException.getValue(ValueOrException.java:67)
  38. at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:33)
  39. at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:343)
  40. at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:216)
  41. at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:118)
  42. ... 11 more
  43. Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; reason: {#method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no queue 'spring-queue-async' in vhost '/', class-id=50, method-id=10), null, ""}
  44. at com.rabbitmq.client.impl.ChannelN.asyncShutdown(ChannelN.java:473)
  45. at com.rabbitmq.client.impl.ChannelN.processAsync(ChannelN.java:313)
  46. at com.rabbitmq.client.impl.AMQChannel.handleCompleteInboundCommand(AMQChannel.java:144)
  47. at com.rabbitmq.client.impl.AMQChannel.handleFrame(AMQChannel.java:91)
  48. at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:533)

控制台添加队列。

 
 

(转) RabbitMQ学习之spring整合发送异步消息的更多相关文章

  1. (转)RabbitMQ学习之spring整合发送异步消息(注解实现)

    http://blog.csdn.net/zhu_tianwei/article/details/40919249 实现使用Exchange类型为DirectExchange. routingkey的 ...

  2. (转) RabbitMQ学习之spring整合发送同步消息(注解实现)

    http://blog.csdn.net/zhu_tianwei/article/details/40918477 上一篇文章通过xml配置rabbitmq的rabbitTemplate,本节将使用注 ...

  3. (转)RabbitMQ学习之spring整合发送同步消息

    http://blog.csdn.net/zhu_tianwei/article/details/40890543 以下实现使用Exchange类型为DirectExchange. routingke ...

  4. 【RocketMQ源码学习】- 3. Client 发送同步消息

    本文较长,代码后面给了方法简图,希望给你帮助 发送的方式 同步发送 异步发送 消息的类型 普通消息 顺序消息 事务消息 发送同步消息的时序图 为了防止读者朋友嫌烦,可以看下时序图,后面我也会给出方法的 ...

  5. ActiveMQ学习总结------Spring整合ActiveMQ 04

    通过前几篇的学习,相信大家已经对我们的ActiveMQ的原生操作已经有了个深刻的概念, 那么这篇文章就来带领大家一步一步学习下ActiveMQ结合Spring的实战操作 注:本文将省略一部分与Acti ...

  6. RabbitMQ学习笔记之五种模式及消息确认机制

    本文详细介绍简单模式Simple.工作模式Work.发布订阅模式Publish/Subscribe.Topic.Routing. Maven依赖引用 <dependencies> < ...

  7. Spring整合ActiveMQ实现消息延迟投递和定时投递

    linux(centos)系统安装activemq参考:https://www.cnblogs.com/pxblog/p/12222231.html 首先在ActiveMQ的安装路径 /conf/ac ...

  8. RabbitMQ走过的坑,发送的消息是乱码

    发送的消息在可视化界面中是乱码,如图: 看见这个content_tpye没有,是不是很奇怪,就是这个坑,设置下就行,看代码: @Bean Jackson2JsonMessageConverter me ...

  9. RabbitMQ学习之spring配置文件rabbit标签的使用

    下面我们通过一个实例看一下rabbit的使用. 1.实现一个消息监听器ReceiveMessageListener.Java package org.springframework.amqp.core ...

随机推荐

  1. MySQL出现no mycat database selected的问题分析

    1.先抛开mycat来处理 2.在查询表时,要指定是哪个数据库,然后再查询. ①.如果再MySQL Workbench中,先使用use tablename;,然后在执行操作语句:或者在语句上指定要查询 ...

  2. VMware 12安装CentOS 6.9时出现:The centos disc was not found in any of your drives.Please insert the centos disc and press OK to retry

    错误: The centos disc was not found in any of your drives.Please insert the centos disc and press OK t ...

  3. linux下apache2更换目录

    修改apache2的默认文档目录(默认是在/var/www) 修改命令:sudo gedit /etc/apache2/sites-enabled/000-default 在文档中找到 Documen ...

  4. Android 删除新版安卓fragment_main.xml

    在新版本号的ADT中,创建androidproject时默认会产生两个xml文件--fragment_main和activity_main. 个人建议把fragment_main这个文件删除掉 1)将 ...

  5. 国内物联网平台初探(三) ——QQ物联·智能硬件开放平台

    平台定位 将QQ帐号体系.好友关系链.QQ消息通道及音视频服务等核心能力提供给可穿戴设备.智能家居.智能车载.传统硬件等领域的合作伙伴,实现用户与设备.设备与设备.设备与服务之间的联动. 实现用户与设 ...

  6. typeof、instanceof、hasOwnProperty()、isPrototypeOf()

    typeof 操作符 instanceof 操作符 hasOwnProperty()方法 isPrototypeOf()方法 1.typeof 用于获取变量的类型,一般只返回以下几个值:string, ...

  7. 【TYVJ1936】【Clover杯NOIP模拟赛IV】太空战队

    [问题描述] 在社会经济高速发展的今天,借助高科技手段,组建太空战队的愿望就快实现了. 战队属下有N个航天员.作为空军选拔上来的佼佼者,每个航天员都有与生俱来的骄傲——他们每个人都认为自己是最强的或者 ...

  8. LVS十种调度算法介绍

    1.轮叫调度(Round Robin)(简称rr) 轮叫调度(Round Robin Scheduling)算法就是以轮叫的方式依次将请求调度不同的服务器,即每次调度执行i = (i + 1) mod ...

  9. B - Calculating Function

    Problem description For a positive integer n let's define a function f: f(n) =  - 1 + 2 - 3 + .. + ( ...

  10. iterator和iterable的区别

    相关博客:  http://blog.csdn.net/lipengcn/article/details/51700153         Java中Iterable和Iterator的辨析 http ...