【RabbitMQ】消息队列RabbitMQ与Spring集成

一、介绍

1.概要

  MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序的通信方法。应用程序通过读写出入队列的消息(针对应用程序的数据)来通信,而无需专用连接来链接它们。消息传递指的是程序之间通过在消息中发送数据进行通信,而不是通过直接调用彼此来通信,直接调用通常是用于诸如远程过程调用的技术。排队指的是应用程序通过 队列来通信。队列的使用除去了接收和发送应用程序同时执行的要求。其中较为成熟的MQ产品有IBM WEBSPHERE MQ等等。

2.MQ特点

  MQ是消费-生产者模型的一个典型的代表,一端往消息队列中不断写入消息,而另一端则可以读取或者订阅队列中的消息。MQ和JMS类似,但不同的是JMS是SUN JAVA消息中间件服务的一个标准和API定义,而MQ则是遵循了AMQP协议的具体实现和产品。
3.使用场景
  在项目中,将一些无需即时返回且耗时的操作提取出来,进行了异步处理,而这种异步处理的方式大大的节省了服务器的请求响应时间,从而提高了系统的吞吐量。
 
二、Spring集成rabbitmq
1.pom配置
<dependency>
      <groupId>org.springframework.amqp</groupId>
      <artifactId>spring-rabbit</artifactId>
      <version>1.2.0.RELEASE</version>
</dependency>

2.rabbmitmq配置文件

mq.host=127.0.0.1
mq.username=test
mq.password=123456
mq.port=5672
mq.vhost=mq

个人习惯,可直接写到相应的xml中,不单独使用properties文件

3.Spring配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:rabbit="http://www.springframework.org/schema/rabbit"
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
           http://www.springframework.org/schema/mvc  
           http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
           http://www.springframework.org/schema/context   
           http://www.springframework.org/schema/context/spring-context-3.2.xsd
           http://www.springframework.org/schema/rabbit
            http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd"
           >
    <!-- 连接配置 -->
    <rabbit:connection-factory id="connectionFactory" host="127.0.0.1" username="test"
        password="123456" port="5672"/>
    <!-- spring template声明-->
    <rabbit:template id="amqpTemplate" connection-factory="connectionFactory"  
    exchange="authExchange"/>  
  
    <rabbit:admin connection-factory="connectionFactory" />  

    <!--路由设置 将队列绑定,属于topic类型-->  
    <rabbit:topic-exchange name="authExchange"/> 
    <!-- 在Spring中使用mq:声明一个消息队列 -->
    <rabbit:queue id="test_queue_key" name="test_queue_key" durable="true" auto-delete="false" exclusive="false" />
</beans> 

durable:是否持久化
exclusive: 仅创建者可以使用的私有队列,断开后自动删除
auto_delete: 当所有消费客户端连接断开后,是否自动删除队列

后续操作请参考:http://blog.csdn.net/jacman/article/details/50261915



posted @ 2017-09-07 09:17  丶会飞的羊  阅读(363)  评论(0编辑  收藏  举报