本文,讲解 Spring Boot 如何集成 RabbitMQ,实现消息队列。

什么是 RabitMQ

RabbitMQ 是一个在 AMQP 基础上完整的,可复用的企业消息系统。

关于 RabbitMQ 的使用,可以阅读之前的 RabbitMQ 实战教程。

Spring Boot 整合 RabbitMQ

Spring Boot 整合 RabbitMQ 是非常容易,只需要两个步骤。

首先,在 pom.xml 中增加 RabbitMQ 依赖。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-amqp</artifactId>
  4. </dependency>

第二步,在 src/main/resources/application.properties 中配置信息。

  1. #rabbitmq
  2. spring.rabbitmq.host=localhost
  3. spring.rabbitmq.port=5672
  4. spring.rabbitmq.username=guest
  5. spring.rabbitmq.password=guest

实战演练

一个简单的实战开始

我们来实现一个简单的发送、接收消息。

Configuration

在 Spring Boot 中使用 @Bean 注册一个队列。

  1. @Configuration
  2. public class RabbitMQConfig {
  3. public static final String QUEUE_NAME = "spring-boot-simple";
  4. @Bean
  5. public Queue queue() {
  6. return new Queue(QUEUE_NAME);
  7. }
  8. }

消息生产者

创建消息生产者 Sender。通过注入 AmqpTemplate 接口的实例来实现消息的发送。

  1. @Service
  2. public class Sender {
  3. @Autowired
  4. private AmqpTemplate rabbitTemplate;
  5. public void send() {
  6. System.out.println("梁桂钊 发送消息...");
  7. rabbitTemplate.convertAndSend(RabbitMQConfig.QUEUE_NAME, "你好, 梁桂钊!");
  8. }
  9. }

消息消费者

创建消息消费者 Receiver。通过 @RabbitListener 注解定义对队列的监听。

  1. @Service
  2. public class Receiver {
  3. @Autowired
  4. private AmqpTemplate rabbitTemplate;
  5. @RabbitListener(queues = "spring-boot-simple")
  6. public void receiveMessage(String message) {
  7. System.out.println("Received <" + message + ">");
  8. }
  9. }

运行

  1. @SpringBootApplication
  2. @EnableAutoConfiguration
  3. @ComponentScan(basePackages = { "com.lianggzone.springboot" })
  4. public class RunMain {
  5. public static void main(String[] args) {
  6. SpringApplication.run(RunMain.class, args);
  7. }
  8. }

单元测试

创建单元测试用例

  1. public class RabbitMQTest {
  2. @Autowired
  3. private Sender sender;
  4. @Test
  5. public void send() throws Exception {
  6. sender.send();
  7. }
  8. }

路由的实战演练

经过上面的实战案例,我们对 Spring Boot 整合 RabbitMQ 有了一定的了解。现在,我们再来看下 RabbitMQ 路由场景。

Configuration

在 RabbitMQConfig 中,我们注册 队列,转发器,监听等。

  1. @Configuration
  2. public class RabbitMQConfig2 {
  3. public static final String QUEUE_NAME = "spring-boot";
  4. public static final String QUEUE_EXCHANGE_NAME = "spring-boot-exchange";
  5. @Bean
  6. public Queue queue() {
  7. // 是否持久化
  8. boolean durable = true;
  9. // 仅创建者可以使用的私有队列,断开后自动删除
  10. boolean exclusive = false;
  11. // 当所有消费客户端连接断开后,是否自动删除队列
  12. boolean autoDelete = false;
  13. return new Queue(QUEUE_NAME, durable, exclusive, autoDelete);
  14. }
  15. @Bean
  16. public TopicExchange exchange() {
  17. // 是否持久化
  18. boolean durable = true;
  19. // 当所有消费客户端连接断开后,是否自动删除队列
  20. boolean autoDelete = false;
  21. return new TopicExchange(QUEUE_EXCHANGE_NAME, durable, autoDelete);
  22. }
  23. @Bean
  24. public Binding binding(Queue queue, TopicExchange exchange) {
  25. return BindingBuilder.bind(queue).to(exchange).with(QUEUE_NAME);
  26. }
  27. @Bean
  28. SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
  29. MessageListenerAdapter listenerAdapter) {
  30. SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
  31. container.setConnectionFactory(connectionFactory);
  32. container.setQueueNames(QUEUE_NAME);
  33. container.setMessageListener(listenerAdapter);
  34. return container;
  35. }
  36. @Bean
  37. MessageListenerAdapter listenerAdapter(Receiver receiver) {
  38. return new MessageListenerAdapter(receiver, "receiveMessage");
  39. }
  40. }

消息生产者

创建消息生产者 Sender。通过注入 AmqpTemplate 接口的实例来实现消息的发送。

  1. @Service
  2. public class Sender {
  3. @Autowired
  4. private AmqpTemplate rabbitTemplate;
  5. public void send() {
  6. System.out.println("梁桂钊 发送消息...");
  7. rabbitTemplate.convertAndSend(RabbitMQConfig2.QUEUE_NAME, "你好, 梁桂钊!");
  8. }
  9. }

消息消费者

创建消息消费者 Receiver。通过 @RabbitListener 注解定义对队列的监听。

  1. @Service
  2. public class Receiver {
  3. public void receiveMessage(String message) {
  4. System.out.println("Received <" + message + ">");
  5. }
  6. }

运行

  1. @SpringBootApplication
  2. @EnableAutoConfiguration
  3. @ComponentScan(basePackages = { "com.lianggzone.springboot" })
  4. public class RunMain {
  5. public static void main(String[] args) {
  6. SpringApplication.run(RunMain.class, args);
  7. }
  8. }

单元测试

创建单元测试用例

  1. public class RabbitMQTest {
  2. @Autowired
  3. private Sender sender;
  4. @Test
  5. public void send() throws Exception {
  6. sender.send();
  7. }
  8. }

源代码

相关示例完整代码: springboot-action

(完)

如果觉得我的文章对你有帮助,请随意打赏。

Spring Boot 揭秘与实战(六) 消息队列篇 - RabbitMQ的更多相关文章

  1. Spring Boot 揭秘与实战 附录 - Spring Boot 公共配置

    Spring Boot 公共配置,配置 application.properties/application.yml 文件中. 摘自:http://docs.spring.io/spring-boot ...

  2. Spring Boot 揭秘与实战 自己实现一个简单的自动配置模块

    文章目录 1. 实战的开端 – Maven搭建 2. 参数的配置 - 属性参数类 3. 真的很简单 - 简单的服务类 4. 自动配置的核心 - 自动配置类 5. spring.factories 不要 ...

  3. Spring Boot 揭秘与实战 源码分析 - 工作原理剖析

    文章目录 1. EnableAutoConfiguration 帮助我们做了什么 2. 配置参数类 – FreeMarkerProperties 3. 自动配置类 – FreeMarkerAutoCo ...

  4. Spring Boot 揭秘与实战 源码分析 - 开箱即用,内藏玄机

    文章目录 1. 开箱即用,内藏玄机 2. 总结 3. 源代码 Spring Boot提供了很多”开箱即用“的依赖模块,那么,Spring Boot 如何巧妙的做到开箱即用,自动配置的呢? 开箱即用,内 ...

  5. Spring Boot 揭秘与实战(九) 应用监控篇 - 自定义监控端点

    文章目录 1. 继承 AbstractEndpoint 抽象类 2. 创建端点配置类 3. 运行 4. 源代码 Spring Boot 提供的端点不能满足我们的业务需求时,我们可以自定义一个端点. 本 ...

  6. Spring Boot 揭秘与实战(九) 应用监控篇 - HTTP 健康监控

    文章目录 1. 内置 HealthIndicator 监控检测 2. 自定义 HealthIndicator 监控检测 3. 源代码 Health 信息是从 ApplicationContext 中所 ...

  7. Spring Boot 揭秘与实战(九) 应用监控篇 - HTTP 应用监控

    文章目录 1. 快速开始 2. 监控和管理端点3. 定制端点 2.1. health 应用健康指标 2.2. info 查看应用信息 2.3. metrics 应用基本指标 2.4. trace 基本 ...

  8. Spring Boot 揭秘与实战(八) 发布与部署 - 远程调试

    文章目录 1. 依赖 2. 部署 3. 调试 4. 源代码 设置远程调试,可以在正式环境上随时跟踪与调试生产故障. 依赖 在 pom.xml 中增加远程调试依赖. <plugins> &l ...

  9. Spring Boot 揭秘与实战(八) 发布与部署 - 开发热部署

    文章目录 1. spring-boot-devtools 实现热部署 2. Spring Loaded 实现热部署 3. 模板文件热部署 4. 源代码 Spring Boot 支持页面与类文件的热部署 ...

随机推荐

  1. 时间序列八: 以NASA之名: 卡尔曼滤波器

    目录 以NASA之名: 卡尔曼滤波器 引言 荣耀骑士 卡尔曼滤波器* 参考文献: 以NASA之名: 卡尔曼滤波器 'That's one small step for man,one giant le ...

  2. 创建型模式篇(工厂模式Factory Pattern)

    一.工厂模式(Factory Pattern) 1.定义: 在软件系统,经常面临着“某个对象”的创建工作,由于需求的变化,这个对象的具体实现经常面临着剧烈的变化,但是它却拥有比较稳定的接口.提供一种封 ...

  3. Thinkphp5 Nginx Pathinfo配置

    server { listen ; server_name sui.com; root /tmmee/sad.cn/public; index index.php index.html index.h ...

  4. 【转】JQuery插件定义

    一:导言 有些WEB开发者,会引用一个JQuery类库,然后在网页上写一写("#"),("."),写了几年就对别人说非常熟悉JQuery.我曾经也是这样的人,直 ...

  5. nodejs 解析excel文件

    app.js: var FileUpload = require('express-fileupload') app.use(FileUpload()); service.js: npm instal ...

  6. Pinpoint是一个开源的 APM (Application Performance Management/应用性能管理)工具,用于基于java的大规模分布式系统,基于Google Dapper论文

    Pinpoint是一个开源的 APM (Application Performance Management/应用性能管理)工具,用于基于java的大规模分布式系统,基于Google Dapper论文 ...

  7. CSS3 的box-shadow进阶之 - 基础知识篇

    box-shadow被认为是CSS3最好的特性之一,发挥想象力,搭配其它属性,可以做出很多好看的效果(如下图,将会放在下一篇文章讲解),这篇文章主要讲一下box-shadow的基础知识.       ...

  8. 利用awk处理学生成绩问题(难度较大)

    学生成绩表单如下: Name,Team,First Test, Second Test, Third Test Tom,Red,,, Joe,Green,,, Maria,Blue,,, Fred,B ...

  9. 锤子科技 Smartisan M1L 咖啡金 真皮背面 高配版 5.7

    http://www.smartisan.com/m1/#/os    快人一步的OS http://www.smartisan.com/shop/#/buyphone?c=coffee&v= ...

  10. day32 信号量 事件 管道 进程池

    今日主要内容: 1.管道(Pipe) 数据接收一次就没有了 2.事件(Event) 3.基于事件的进程通信 4.信号量(Semaphore) 5. 进程池(重点) 6.进程池的同步方法和异步方法 7. ...