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

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

        <dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.6.0.RELEASE</version>
</dependency>

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

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

二:配置生成者

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

三:生产者程序

public class Spittle implements Serializable {
private Long id;
private Spitter spitter;
private String message;
private Date postedTime; public Spittle(Long id, Spitter spitter, String message, Date postedTime) {
this.id = id;
this.spitter = spitter;
this.message = message;
this.postedTime = postedTime;
} public Long getId() {
return this.id;
} public String getMessage() {
return this.message;
} public Date getPostedTime() {
return this.postedTime;
} public Spitter getSpitter() {
return this.spitter;
}
}
public class ProducerMain {
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("amqp/amqp-producer.xml");
AmqpTemplate template = (AmqpTemplate) context.getBean("rabbitTemplate");
for (int i = 0; i < 20; i++) {
System.out.println("Sending message #" + i);
Spittle spittle = new Spittle((long) i, null, "Hello world (" + i + ")", new Date());
template.convertAndSend(spittle);
Thread.sleep(5000);
}
System.out.println("Done!");
}
}

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

第四个:消费者程序

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

/**
* Created by Administrator on 2016/11/18.
*/
public class SpittleAlertHandler implements MessageListener {
@Override
public void onMessage(Message message) {
try {
String body=new String(message.getBody(),"UTF-8");
System.out.println(body);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}

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

下面我们配置消费者

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

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

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

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

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

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

下面是消费者监听配置

 <rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto">
<rabbit:listener queues="spring-test-queue1" method="onMessage" ref="queueListenter"></rabbit:listener>
</rabbit:listener-container>
<rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto">
<rabbit:listener queues="spring-test-queue2" method="onMessage" ref="queueListenter"></rabbit:listener>
</rabbit:listener-container>

下面是程序

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

实际情况可能需要我们去分离消费者和生成者的程序。当然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. linux 查找文件和搜索文件

    按照文件名搜索 find . -name 'file name' grep -lr 'content'  filepath

  2. docker 1.8+之后ubuntu安装指定版本docker-engine

    这边记录ubuntu安装过程,首先是官网文档 If you haven’t already done so, log into your Ubuntu instance. Open a termina ...

  3. Xamarin笔记

    Xamarin学习笔记 1. Xamarin Studio自动更新下载的安装文件缓存路径:C:\Users\登录用户\AppData\Local\XamarinStudio-5.0\Cache\Tem ...

  4. mysql_connect() php7不支持,php5.5可以,是废弃函数

    天用了PHP7,发现和PHP5变化还挺大的,最大的就是MySQL的连接库变了. PHP5中使用mysql_connect()函数进行连接,但实际上,PHP5.5开始,MySQL就不推荐使用了,属于废弃 ...

  5. Oracle分区

    可以参考文档:http://docs.oracle.com/cd/E18283_01/server.112/e16541/part_admin001.htm#insertedID0 (支持11g和12 ...

  6. 自动ftp上传文件脚本

    方法一: echo "open 21.244.88.129 user glxtftp glbzuser bin prompt off cd /glxt/DBINFO lcd /tmp put ...

  7. ASP.NET中获取Repeater模板列中LinkButton按钮事件中获取ID等

    前台页面中: <asp:Repeater ID="repComment" runat="server">            <ItemTe ...

  8. 第一个Mac shell 小脚本

    大多数程序员都喜欢偷懒的,我也不例外.相信好多Android开发的coder 在网络http请求方面,会浪费很多时间在接口调试这里..有时候,自己写了一个小测试,行还好,不行的话,还要跟写后台的哥们一 ...

  9. jsonp帮助你知道你关注的他或她喜欢什么歌曲

    利用腾讯提供的QQ音乐API,返回一段对方在QQ音乐收藏的歌曲名称json数据,并对该json做解析,就能知道你的那个他或她喜欢听什么歌曲了,然后你就知道他/她的品位了,然后就自己看着办了,嘿嘿.我只 ...

  10. Torch7 Tensor切片总结

    1.narrow(k,m,n) 这个函数是选中第k维的从m行开始,供选中n行 2.sub(dim1s,dim1e[,dim2s,dim2e,..,dim4s,dim4e]) 功能最强大,可以切任意的一 ...