上篇文章RabbitMQ基础入门学习了rabbitMQ一些基础的api,当然spring也在原生代码的基础上做了更多的封装,这篇文章就基于spring-rabbit,学习一下spring的实现。

引入jar:

<dependency>

<groupId>org.springframework.amqp</groupId>

<artifactId>spring-rabbit</artifactId>

<version>1.5.0.RELEASE</version>

</dependency>

上篇文章没有测试到Topic exchange,下面就使用Topic exchange做测试。

1.基于springframework.amqp.rabbit java写法。

 import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter; @RabbitListener(queues = "hello")
public class Tut1Java { public static void main(final String... args) throws Exception { CachingConnectionFactory cf = new CachingConnectionFactory();
cf.setAddresses("192.168.1.7:5672");
cf.setUsername("admin");
cf.setPassword("admin"); // 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("Tut1Java " + foo);
}
};
MessageListenerAdapter adapter = new MessageListenerAdapter(listener);
container.setMessageListener(adapter);
container.setQueueNames("myQueue");
container.start(); // send something
RabbitTemplate template = new RabbitTemplate(cf);
// 只有routingKey符合foo.*规则的才会被接受处理
template.convertAndSend("myExchange", "foo.bar", "Hello, world!");
container.stop();
}
}

整块代码可以简单的实现了发送接收消息,主要分为四个部分。

16~19行 初始化一个CachingConnectionFactory,其实底层也是原生的ConnectionFactory。

22~27行 主要是设置queue和exchange,并把它们按照"foo.*"的路由规则绑定起来。

  new Queue("myQueue"),创建一个本地持久话名字叫myQueue的队列。

  declareQueue(queue),声明一个队列。

  new TopicExchange("myExchange"),创建一个topic exchange,看名字也知道exchange类型是topic,我们只要传递参数就好了。当然也会有FanoutExchange、DirectExchange、HeadersExchange。

  BindingBuilder.bind(queue).to(exchange).with("foo.*"),将queue绑定到exchange上,并以"foo.*"作为他们之间的路由规则。

30~40行 主要是通过SimpleMessageListenerContainer去监听消息,并且可以设置特定类的方法去执行处理接受到的消息。

Object listener = new Object() {
// 接受到消息时,会执行此方法
public void handleMessage(String foo) {
System.out.println("Tut1Java " + foo );
}
public void handleMessage2(String foo) {
System.out.println("Tut1Java2 " + foo);
}
};
MessageListenerAdapter adapter = new MessageListenerAdapter(listener);
adapter.setDefaultListenerMethod("handleMessage2");
container.setMessageListener(adapter);

如果消息监听写成上面这样,那么将执行handleMessage2(String foo) 。

43~46行 利用RabbitTemplate发送消息,三个参数依次为exchange、routingKey和发送的消息,

首先exchange名称要和admin声明的一致,routingKey要符合当前topic exchange的路由规则,否则消息不会发送到当前队列中。

再看一下topic exchange的模型:

最后运行一下,可以发现消息被顺利打印出来了。

2.基于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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"> <rabbit:connection-factory id="connectionFactory" username="admin" password="admin" host="192.168.1.7" port="5672" virtual-host="/" /> <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="rabbitMQ.springAMQP.Foo" /> </beans>

在context.xml中可以看到很多熟悉的rabbitMQ的对象,这种写法只不过从上面new出来的对象,改为使用spring的xml去声明各种bean对象。

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Tut1Spring { public static void main(final String... args) throws Exception { AbstractApplicationContext ctx =
new ClassPathXmlApplicationContext("spring/context.xml");
RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
template.convertAndSend("Tut1Spring " + "Hello, world!");
Thread.sleep(1000);
ctx.destroy();
}
}
public class Foo {

    public void listen(String foo) {
System.out.println("Foo=" + foo);
}
}

Foo为处理接受并处理消息的类,在xml中也指定了执行的方法为listen。

最后运行一下,可以发现消息被顺利打印出来了。

其实无论是哪种方式的实现,内部本质还是基于最原生的api,我们只要理解最基础的部分,这些理解起来还是比较容易的。

















RabbitMQ-Spring AMQP的更多相关文章

  1. 译: 1. RabbitMQ Spring AMQP 之 Hello World

    本文是译文,原文请访问:http://www.rabbitmq.com/tutorials/tutorial-one-spring-amqp.html RabbitMQ 是一个Brocker (消息队 ...

  2. 译: 2. RabbitMQ Spring AMQP 之 Work Queues

    在上一篇博文中,我们写了程序来发送和接受消息从一个队列中. 在这篇博文中我们将创建一个工作队列,用于在多个工作人员之间分配耗时的任务. Work Queues 工作队列(又称:任务队列)背后的主要思想 ...

  3. 译: 3. RabbitMQ Spring AMQP 之 Publish/Subscribe 发布和订阅

    在第一篇教程中,我们展示了如何使用start.spring.io来利用Spring Initializr创建一个具有RabbitMQ starter dependency的项目来创建spring-am ...

  4. 译: 6. RabbitMQ Spring AMQP 之 RPC

    Remote procedure call (RPC) 在第二篇教程中,我们学习了如何使用工作队列在多个工作人员之间分配耗时的任务. 但是如果我们需要在远程计算机上运行一个函数并等待结果呢?嗯,这是一 ...

  5. 译: 4. RabbitMQ Spring AMQP 之 Routing 路由

    在上一个教程中,我们构建了一个简单的fanout(扇出)交换.我们能够向许多接收者广播消息. 在本教程中,我们将为其添加一个功能 - 我们将只能订阅一部分消息.例如,我们将只能将消息指向感兴趣的特定颜 ...

  6. 译: 5. RabbitMQ Spring AMQP 之 Topic 主题

    在上一个教程中,我们提高了消息传递的灵活 我们使用direct交换而不是使用仅能够进行虚拟广播的fanout交换, 并且获得了基于路由key 有选择地接收消息的可能性. 虽然使用direct 交换改进 ...

  7. spring amqp rabbitmq fanout配置

    基于spring amqp rabbitmq fanout配置如下: 发布端 <rabbit:connection-factory id="rabbitConnectionFactor ...

  8. 深入剖析 RabbitMQ —— Spring 框架下实现 AMQP 高级消息队列协议

    前言 消息队列在现今数据量超大,并发量超高的系统中是十分常用的.本文将会对现时最常用到的几款消息队列框架 ActiveMQ.RabbitMQ.Kafka 进行分析对比.详细介绍 RabbitMQ 在 ...

  9. 消息中间件——RabbitMQ(九)RabbitMQ整合Spring AMQP实战!(全)

    前言 1. AMQP 核心组件 RabbitAdmin SpringAMQP声明 RabbitTemplate SimpleMessageListenerContainer MessageListen ...

  10. RabbitMQ与Spring的框架整合之Spring AMQP实战

    1.SpringAMQP用户管理组件RabbitAdmin. RabbitAdmin类可以很好的操作RabbitMQ,在Spring中直接进行注入即可.注意,autoStartup必须设置为true, ...

随机推荐

  1. PV & PVC - 每天5分钟玩转 Docker 容器技术(150)

    Volume 提供了非常好的数据持久化方案,不过在可管理性上还有不足. 拿前面 AWS EBS 的例子来说,要使用 Volume,Pod 必须事先知道如下信息: 当前 Volume 来自 AWS EB ...

  2. Mego(1) - NET中主流ORM框架性能对比

    从刚刚开始接触ORM到现在已有超过八年时间,用过了不少ORM框架也了解了不少ORM框架,看过N种关于ORM框架的相关资料与评论,各种言论让人很难选择.在ORM的众多问题中最突出的问题是关于性能方面的问 ...

  3. 使用JavaScript实现一个俄罗斯方块

    清明假期期间,闲的无聊,就做了一个小游戏玩玩,目前游戏逻辑上暂未发现bug,只不过样子稍微丑了一些-.-项目地址:https://github.com/Jiasm/tetris在线Demo:http: ...

  4. Linq 大合集

    static void Main(string[] args) { string[] words = { "zero", "one", "two&qu ...

  5. eclipse怎么停止building workspace

    Eclipse 一直不停 building workspace完美解决总结 一.产生这个问题的原因多种 1.自动升级 2.未正确关闭 3.maven下载lib挂起 等.. 二.解决总结 (1).解决方 ...

  6. SQL Server 利用触发器对多表视图进行更新

    其步骤就是:利用update操作触发器产生的2个虚拟表[inserted]用来存储修改的数据信息和[deleted]表,然后将对应的数据更新到对应数据表中的字段信息中: 1.首先创建3个表: a.信息 ...

  7. log4j将日志文件输出到相对路径

    建议直接使用jvm中定义的变量或者操作系统的环境变量. log4j.appender.logfile.File=${user.dir}/logs/app.log,使用tomcat容器时${user.d ...

  8. Hibernate HQL中的子查询

    子查询是SQL语句中非常重要的功能特性,它可以在SQL语句中利用另外一条SQL语句的查询结果,在Hibernate中HQL查询同样对子查询功能提供了支持.   如下面代码所示: List list=s ...

  9. Iframe父页面与子页面之间的相互调用

    iframe元素就是文档中的文档. window对象: 浏览器会在其打开一个HTML文档时创建一个对应的window对象.但是,如果一个文档定义了一个或者多个框架(即:包含一个或者多个frame或者i ...

  10. 原生js的一些研究和总结(1)

    数据类型 基本类型值包括: undefined,null,Boolean,Number和String,这些类型分别在内存中占有固定的大小空间,它们的值保存在栈空间,我们通过按值来访问的. 引用类型包括 ...