这篇文章带你了解怎么整合RabbitMQ服务器,并且通过它怎么去发送和接收消息。我将构建一个springboot工程,通过RabbitTemplate去通过MessageListenerAdapter去订阅一个POJO类型的消息。

准备工作

  • 15min

  • IDEA

  • maven 3.0

在开始构建项目之前,机器需要安装rabbitmq,你可以去官网下载,http://www.rabbitmq.com/download.html ,如果你是用的Mac(程序员都应该用mac吧),你可以这样下载:

brew install rabbitmq

安装完成后开启服务器:

rabbitmq-server

开启服务器成功,你可以看到以下信息:

            RabbitMQ 3.1.3. Copyright (C) 2007-2013 VMware, Inc.
##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
##  ##
##########  Logs: /usr/local/var/log/rabbitmq/rabbit@localhost.log
######  ##        /usr/local/var/log/rabbitmq/rabbit@localhost-sasl.log
##########Starting broker... completed with 6 plugins.

构建工程

构架一个SpringBoot工程,其pom文件依赖加上spring-boot-starter-amqp的起步依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency>

创建消息接收者

在任何的消息队列程序中,你需要创建一个消息接收者,用于响应发送的消息。

@Component
public class Receiver {private CountDownLatch latch = new CountDownLatch(1);public void receiveMessage(String message) {System.out.println("Received <" + message + ">");latch.countDown();}public CountDownLatch getLatch() {return latch;}}

消息接收者是一个简单的POJO类,它定义了一个方法去接收消息,当你注册它去接收消息,你可以给它取任何的名字。其中,它有CountDownLatch这样的一个类,它是用于告诉发送者消息已经收到了,你不需要在应用程序中具体实现它,只需要latch.countDown()就行了。

创建消息监听,并发送一条消息

在spring程序中,RabbitTemplate提供了发送消息和接收消息的所有方法。你只需简单的配置下就行了:

  • 需要一个消息监听容器

  • 声明一个quene,一个exchange,并且绑定它们

  • 一个组件去发送消息

代码清单如下:

package com.forezp;import com.forezp.message.Receiver;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;@SpringBootApplication
public class SpringbootRabbitmqApplication {final static String queueName = "spring-boot";@BeanQueue queue() {return new Queue(queueName, false);}@BeanTopicExchange exchange() {return new TopicExchange("spring-boot-exchange");}@BeanBinding binding(Queue queue, TopicExchange exchange) {return BindingBuilder.bind(queue).to(exchange).with(queueName);}@BeanSimpleMessageListenerContainer container(ConnectionFactory connectionFactory,MessageListenerAdapter listenerAdapter) {SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();container.setConnectionFactory(connectionFactory);container.setQueueNames(queueName);container.setMessageListener(listenerAdapter);return container;}@BeanMessageListenerAdapter listenerAdapter(Receiver receiver) {return new MessageListenerAdapter(receiver, "receiveMessage");}public static void main(String[] args) {SpringApplication.run(SpringbootRabbitmqApplication.class, args);}
}

创建一个测试方法:

@Component
public class Runner implements CommandLineRunner {private final RabbitTemplate rabbitTemplate;private final Receiver receiver;private final ConfigurableApplicationContext context;public Runner(Receiver receiver, RabbitTemplate rabbitTemplate,ConfigurableApplicationContext context) {this.receiver = receiver;this.rabbitTemplate = rabbitTemplate;this.context = context;}@Overridepublic void run(String... args) throws Exception {System.out.println("Sending message...");rabbitTemplate.convertAndSend(Application.queueName, "Hello from RabbitMQ!");receiver.getLatch().await(10000, TimeUnit.MILLISECONDS);context.close();}}

启动程序,你会发现控制台打印:

Sending message...
Received <Hello from RabbitMQ!>

总结

恭喜!你刚才已经学会了如何通过spring raabitmq去构建一个消息发送和订阅的程序。 这仅仅是一个好的开始,你可以通过spring-rabbitmq做更多的事,点击这里。

源码下载:https://github.com/forezp/SpringBootLearning

参考资料

https://spring.io/guides/gs/messaging-rabbitmq/

SpringBoot第十五篇:Springboot整合RabbitMQ相关推荐

  1. SpringBoot第二十五篇:2小时学会springboot

    一.什么是spring boot Takes an opinionated view of building production-ready Spring applications. Spring ...

  2. 跟我学springboot(十五)springboot日志选型

    1.常见的日志框架 JUL.JCL.Jboss-logging.logback.log4j.log4j2.slf4j-. 2.框架区别 日志门面 (日志的抽象层) 日志实现 JCL(Jakarta C ...

  3. springboot系列十五、springboot集成PageHelper

    一.介绍 项目中经常会遇到分页,PageHelper为我们解决了这个问题.本质上实现了Mybatis的拦截器,作了分页处理. 二.配置PageHelper 1.引入依赖 pagehelper-spri ...

  4. 坚持的力量 第十五篇

    第十五篇        漩涡鸣人 从他身上,我看到了进步和向上的力量,经别人推荐,我发现我渐渐的喜欢上了<火影忍者>. 首先,<火影>中的歌曲很有震撼力和穿透力,产生心灵的共鸣 ...

  5. 秒杀多线程第十五篇 关键段,事件,互斥量,信号量的“遗弃”问题

    秒杀多线程第十五篇 关键段,事件,互斥量,信号量的"遗弃"问题 在<秒杀多线程第九篇 经典线程同步总结 关键段 事件 互斥量 信号量>中对经典多线程同步互斥问题进行了回 ...

  6. CCIE理论-第十五篇-IPV6-重分布+ACL+前缀列表

    CCIE理论-第十五篇-IPV6-重分布+ACL+前缀列表 重分布前面讲过,这里再讲一次+实操+效果看看 在ipv6中重分布直连路由是需要加上include-connected的 环境 就这么简单哈, ...

  7. CCIE-LAB-第十五篇-IPV6-BGP+VPN6+RT

    CCIE-LAB-第十五篇-IPV6-BGP+VPN6+RT 实际中,思科只会给你5个小时去做下面的全部配置 这个是CCIE-LAB的拓扑图 问题 翻译: 根据这些要求,将IPV6连接从总部通过SP扩 ...

  8. CCNP-第十五篇-VXLAN(一)

    CCNP-第十五篇-VXLAN(一) 到了这个阶段呢,怎么说呢,简单的NP级别的交换我都跳过去了,但是后期会补, 所以这个衔接可能新手或者不会的看的有的迷茫 但是出自个人原因只好这么干了,VXLAN3 ...

  9. CCNA-第十五篇-DHCP配置+SDN介绍(最后一章)

    CCNA-第十五篇-DHCP配置+SDN介绍 各位好,如果有一直看下来的谢谢支持 这里是CCNA的最后一篇了,如果真的能吸收很多内容,那么普通的东西基本上都没什么大问题了.除非就是工作经验 下一篇就到 ...

最新文章

  1. 不可错过的javascript迷你库
  2. Android中读取NFC标签卡中的ID
  3. ifelse语句是否必须以else结尾?
  4. oracle捕捉所有异常,如何捕获和处理特定的Oracle异常?
  5. [转载] PyTorch: 序列到序列模型(Seq2Seq)实现机器翻译实战
  6. PX4 vision_to_mavros定位
  7. python不带颜色的图形_用python给黑白图像上色
  8. 谈一下今天的网络赛。。。这次是真的弱爆了。。。。
  9. 如何写出优质干净的代码,这6个技巧你不能错过
  10. kafka topic:1_Topic️主题建模:超越令牌输出
  11. java snmp walk,snmpwalk命令常用方法总结(转)
  12. Qt编写地图综合应用30-世界地图
  13. 如何准确的定级_等保三级与等保二级
  14. 微云直链解析php,用微云做直链
  15. 邓紫棋歌曲计算机音乐数字,邓紫棋播放量最高的十首歌曲
  16. APP自动化遇到问题总结-持续更新
  17. java-net-php-python-jspm驾驶培训系统计算机毕业设计程序
  18. 二十一世纪大学英语读写教程(第四册)学习笔记(原文)——3 - How to Change Your Point of View(如何改变你的观点)
  19. 简历快投啊!!!!!!!!!!!!!!!(转自水木)
  20. 【Bug】HTC Vive Pro连接电脑后,一带在头上就会发生卡顿现象,头盔内白屏,信号丢失

热门文章

  1. POJ 1144 Network (求割点)
  2. JS 实现可停顿的垂直滚动
  3. 【WA】九度OJ题目1435:迷瘴
  4. [分享]C# 获取Outlook帐号和密码
  5. 四月青少年编程组队学习(Python一级)Task01
  6. 技术图文:如何在Python中定义二维数组?
  7. 七天学会「股票数据分析软件」的开发(下)
  8. 七天学会「股票数据分析软件」的开发(中)
  9. 【ACM】杭电OJ 2034
  10. 几经沉浮,人工智能前路何方?