上篇文章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. javascript参数传递中处理+号

    在传值过程中,如果+号也是值的一部分,那就需要对+号进行处理.否则+号会被过滤掉. 处理方式:只需要把js中传过去的+号替换成base64 编码 %2B encodeURI(str).replace( ...

  2. eclipse maven项目目录

    今天遇见一个错误,关于eclipse项目的路径问题,web-inf的路径,上图和下图出现了两种web-INF,src的web-INFf和webContent的web-INF,src里面的文件需要编译以 ...

  3. 新概念英语(1-95)Tickets,please!

    Lesson 95 Tickets, please. 请把车票拿出来. Listen to the tape then answer this question. Why did George and ...

  4. SpringCloud的微服务网关:zuul(理论)

    参考链接:https://springcloud.cc/spring-cloud-dalston.html 一.概念与定义 1.为什么要引入API网关 后期维护:路由规则和服务实例列表困难 系统架构: ...

  5. DevExpress控件的一些快捷操作

    用的DevExpress控件时,有一些操作并不太方便,根据我自己需要的封装了一些控件的事件,调用的时候直接绑定控件的事件就可以了 例如: this.ComboBoxEdit.KeyDown += Ct ...

  6. windows系统设置虚拟机开机自启并运行虚拟系统

    简述 很多用windows系统电脑开发的童鞋,会在自己电脑上装一个虚拟机,然后在装一个linux系统当作服务器来使用. 但每次电脑开机都要去重启一下虚拟机电源,实在是不划算.下面博主教大家在windo ...

  7. spark分区数,task数目,core数,worker节点个数,excutor数量梳理

    作者:王燚光链接:https://www.zhihu.com/question/33270495/answer/93424104来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明 ...

  8. 使用net.sf.cssbox实现网页截图

    需要引用包,在pom.xml中添加引用: <dependency> <groupId>net.sf.cssbox</groupId> <artifactId& ...

  9. Hibernate(二):MySQL server version for the right syntax to use near 'type=InnoDB' at line x

    目前使用的hibernate5.2.9版本,配置的mysql方言为: <property name="hibernate.dialect">org.hibernate. ...

  10. CSS3 3D transform变换

    .实际应用-图片的旋转木马效果 您可以狠狠地点击这里:图片的旋转木马效果demo 建议在足够新版本的FireFox浏览器或Safari浏览器下观看,Chrome可能需要居中定位查看,下图为效果缩略图: ...