前面几篇讲解了如何使用rabbitMq,这一篇主要讲解spring集成rabbitmq。

首先引入配置文件org.springframework.amqp,如下

  1. <dependency>
  2. <groupId>org.springframework.amqp</groupId>
  3. <artifactId>spring-rabbit</artifactId>
  4. <version>1.6.0.RELEASE</version>
  5. </dependency>

一:配置消费者和生成者公共部分

  1. <rabbit:connection-factory id="connectionFactory" host="${rabbit.hosts}"
  2. port="${rabbit.port}" username="${rabbit.username}" password="${rabbit.password}" virtual-host="${rabbit.virtualHost}"
  3. channel-cache-size="50"/>
  4. <rabbit:admin connection-factory="connectionFactory"/>
  5. <!--定义消息队列-->
  6. <rabbit:queue name="spittle.alert.queue.1" durable="true" auto-delete="false"/>
  7. <rabbit:queue name="spittle.alert.queue.2" durable="true" auto-delete="false"/>
  8. <rabbit:queue name="spittle.alert.queue.3" durable="true" auto-delete="false"/>
  9. <!--绑定队列-->
  10. <rabbit:fanout-exchange id="spittle.fanout" name="spittle.fanout" durable="true">
  11. <rabbit:bindings>
  12. <rabbit:binding queue="spittle.alert.queue.1"></rabbit:binding>
  13. <rabbit:binding queue="spittle.alert.queue.2"></rabbit:binding>
  14. <rabbit:binding queue="spittle.alert.queue.3"></rabbit:binding>
  15. </rabbit:bindings>
  16. </rabbit:fanout-exchange>

二:配置生成者

  1. <import resource="amqp-share.xml"/>
  2. <!--创建消息队列模板-->
  3. <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"
  4. exchange="spittle.fanout" message-converter="jsonMessageConverter">
  5. </rabbit:template>
  6. <bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.JsonMessageConverter"></bean>

三:生产者程序

  1. public class Spittle implements Serializable {
  2. private Long id;
  3. private Spitter spitter;
  4. private String message;
  5. private Date postedTime;
  6.  
  7. public Spittle(Long id, Spitter spitter, String message, Date postedTime) {
  8. this.id = id;
  9. this.spitter = spitter;
  10. this.message = message;
  11. this.postedTime = postedTime;
  12. }
  13.  
  14. public Long getId() {
  15. return this.id;
  16. }
  17.  
  18. public String getMessage() {
  19. return this.message;
  20. }
  21.  
  22. public Date getPostedTime() {
  23. return this.postedTime;
  24. }
  25.  
  26. public Spitter getSpitter() {
  27. return this.spitter;
  28. }
  29. }
  1. public class ProducerMain {
  2. public static void main(String[] args) throws Exception {
  3. ApplicationContext context = new ClassPathXmlApplicationContext("amqp/amqp-producer.xml");
  4. AmqpTemplate template = (AmqpTemplate) context.getBean("rabbitTemplate");
  5. for (int i = 0; i < 20; i++) {
  6. System.out.println("Sending message #" + i);
  7. Spittle spittle = new Spittle((long) i, null, "Hello world (" + i + ")", new Date());
  8. template.convertAndSend(spittle);
  9. Thread.sleep(5000);
  10. }
  11. System.out.println("Done!");
  12. }
  13. }

其中convertAndSend方法默认第一个参数是交换机名称,第二个参数是路由名称,第三个才是我们发送的数据,现在我们启动程序,效果如下

第四个:消费者程序

首先编写一个用于监听生产者发送信息的代码

  1. /**
  2. * Created by Administrator on 2016/11/18.
  3. */
  4. public class SpittleAlertHandler implements MessageListener {
  5. @Override
  6. public void onMessage(Message message) {
  7. try {
  8. String body=new String(message.getBody(),"UTF-8");
  9. System.out.println(body);
  10. } catch (UnsupportedEncodingException e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. }

一定要注意实现MessageListener,我们只需要获取message的body即可,通过json来转换我们需要的程序(比如我们可以发送一个map,map存放方法和实体,这样我们可以通过反射来调用不同的程序来运行)。

下面我们配置消费者

  1. <import resource="amqp-share.xml"/>
  2. <rabbit:listener-container connection-factory="connectionFactory">
  3. <rabbit:listener ref="spittleListener" method="onMessage" queues="spittle.alert.queue.1,spittle.alert.queue.3,spittle.alert.queue.2"/>
  4. </rabbit:listener-container>
  5. <bean id="spittleListener" class="com.lp.summary.rabbitmq.impl.SpittleAlertHandler"/>

其中spittleListener是监听的程序,method是执行的方法,queues是我们监听的队列,多个队列可以逗号隔开(因为我们采用的是分发,所以三个队列获取的消息是相同的,这里为了简便我放在一个监听程序中了,其实我们可以写三个消费者,每个消费者监听一个队列)

现在只需要启动程序即可运行

  1. public class ConsumerMain {
  2. public static void main(String[] args) {
  3. ApplicationContext context = new ClassPathXmlApplicationContext("amqp/amqp-consumer.xml");
  4. }
  5. }

当然direct跟上面的情况差不多,只不过这个是根据路由匹配,先把数据发送到交换机,然后绑定路由和队列,通过交换机id和路由来找到队列,下面是一些主要的配置

  1. <rabbit:queue id="spring-test-queue1" durable="true" auto-delete="false" exclusive="false" name="spring-test-queue1"></rabbit:queue>
  2. <rabbit:queue name="spring-test-queue2" durable="true" auto-delete="false" exclusive="false"></rabbit:queue>
  3. <!--交换机定义-->
  4. <!--rabbit:direct-exchange:定义exchange模式为direct,
  5. 意思就是消息与一个特定的路由键完全匹配,才会转发。
  6. rabbit:binding:设置消息queue匹配的key-->
  7. <rabbit:direct-exchange name="${rabbit.exchange.direct}" durable="true" auto-delete="false" id="${rabbit.exchange.direct}">
  8. <rabbit:bindings>
  9. <rabbit:binding queue="spring-test-queue1" key="spring.test.queueKey1"/>
  10. <rabbit:binding queue="spring-test-queue2" key="spring.test.queueKey2"/>
  11. </rabbit:bindings>
  12. </rabbit:direct-exchange>
  13.  
  14. <!--spring template声明-->
  15. <rabbit:template exchange="${rabbit.exchange.direct}" id="rabbitTemplate" connection-factory="connectionFactory"
  16. message-converter="jsonMessageConverter"></rabbit:template>
  17. <!--消息对象转成成json-->
  18. <bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.JsonMessageConverter"></bean>

下面是消费者监听配置

  1. <rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto">
  2. <rabbit:listener queues="spring-test-queue1" method="onMessage" ref="queueListenter"></rabbit:listener>
  3. </rabbit:listener-container>
  4. <rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto">
  5. <rabbit:listener queues="spring-test-queue2" method="onMessage" ref="queueListenter"></rabbit:listener>
  6. </rabbit:listener-container>

下面是程序

  1. public static void main(String[] args) {
  2. ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext-rabbitmq-producer.xml");
  3. MQProducer mqProducer=(MQProducer) context.getBean("mqProducer");
  4. mqProducer.sendDateToQueue("spring.test.queueKey1","Hello World spring.test.queueKey1");
  5. mqProducer.sendDateToQueue("spring.test.queueKey2","Hello World spring.test.queueKey2");
  6. }

实际情况可能需要我们去分离消费者和生成者的程序。当然spring还有负载均衡的配置,这里就不多介绍了。

rabbitMQ第五篇:Spring集成RabbitMQ的更多相关文章

  1. RabbitMQ第四篇:Spring集成RabbitMQ

    前面几篇讲解了如何使用rabbitMq,这一篇主要讲解spring集成rabbitmq. 首先引入配置文件org.springframework.amqp,如下 <dependency> ...

  2. spring集成rabbitMq(非springboot)

    首先 , pom文件需要加入spring集成rabbitMq的依赖: <dependency> <groupId>org.springframework.amqp</gr ...

  3. RabbitMQ入门到进阶(Spring整合RabbitMQ&SpringBoot整合RabbitMQ)

    1.MQ简介 MQ 全称为 Message Queue,是在消息的传输过程中保存消息的容器.多用于分布式系统 之间进行通信. 2.为什么要用 MQ 1.流量消峰 没使用MQ 使用了MQ 2.应用解耦 ...

  4. SSM框架开发web项目系列(五) Spring集成MyBatis

    前言 在前面的MyBatis部分内容中,我们已经可以独立的基于MyBatis构建一个数据库访问层应用,但是在实际的项目开发中,我们的程序不会这么简单,层次也更加复杂,除了这里说到的持久层,还有业务逻辑 ...

  5. spring集成RabbitMQ配置文件详解(生产者和消费者)

    1,首先引入配置文件org.springframework.amqp,如下: <dependency> <groupId>org.springframework.amqp< ...

  6. Spring 集成 RabbitMQ

    pom.xml <dependency> <groupId>org.springframework.amqp</groupId> <artifactId> ...

  7. spring集成rabbitmq

    https://www.cnblogs.com/nizuimeiabc1/p/9608763.html

  8. MongoDB的使用学习之(五)Spring集成MongoDB以及简单的CRUD

    这篇文章不错:Spring Data - MongoDB 教程 (1.0.0.M1)http://miller-cn.iteye.com/blog/1258859 1.介绍 之前在很多地方一直见到这个 ...

  9. shiro实战系列(十五)之Spring集成Shiro

    Shiro 的 JavaBean 兼容性使得它非常适合通过 Spring XML 或其他基于 Spring 的配置机制.Shiro 应用程序需要一个具 有单例 SecurityManager 实例的应 ...

随机推荐

  1. SqlServer查询表中各列名称、表中列数

    查询表名为tb_menu的所有列名 select name from syscolumns where id=object_id('tb_menu')     查询表名为tb_menu的所有列名个数 ...

  2. js接收对象类型数组的服务端、浏览器端实现

    1.服务端 JSONArray jsonArr = JSONUtil.generateObjList(objList); public static generateObjList(List<O ...

  3. js实现输入框数量加减【转】

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  4. js get browser vertion (js获取浏览器信息版本)

    1问题:js get browser vertion (js获取浏览器信息版本) 2解决方案 Copy this script into your JavaScript files. It works ...

  5. 解决python编码格式错误问题

    一:前言 遇到问题:print输入汉字时提示错误信息 UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1: o ...

  6. bootstrap学习笔记【转】

    bootstrap是由Twitter公司研发的一个基于HTML,CSS,JavaScript的开源框架,最重要的部分是它的响应式布局.(国内文档翻译官网:http://www.bootcss.com/ ...

  7. Ubuntu Java 环境变量

    方法1:修改/etc/profile 文件所有用户的 shell都有权使用这些环境变量<1>在 shell终端执行命令:vi /etc/profile<2>在 profile文 ...

  8. Web开发者需养成的好习惯

    Web开发者需养成的8个好习惯 每个行业有着每个行业的标准和一些要求,自己只是一个进入前端领域的小白,但是深刻的知道,习惯很重要,就Web开发分享一下,要养成的一些好的习惯. 优秀的Web开发人员工作 ...

  9. OPENDATASOURCE读取远程数据库数据中文乱码问题-sqlserver R2

    insert into kraft_sync_Store(StoreName,StoreCode,Province,PrefectureCity,CountyCity,Region,Area,Unit ...

  10. H5 表单

    伴随着互联网富应用以及移动开发的兴起,传统的Web表单已经越来越不能满足开发的需求,HTML5在Web表单方向也做了很大的改进,如拾色器.日期/时间组件等,使表单处理更加高效. 1.1新增表单类型 - ...