当前位置: 首页 > news >正文

Learn RabbitMQ with SpringBoot

文章目录

  • What is RabbitMQ?
  • RabbitMQ Core concept
  • RabbitMQ Architecture
  • Install and setup RabbitMQ using Docker
  • Explore RabbitMQ using management UI
  • Create and setup Springboot3 project in intellij
  • Springboot and RabbitMQ Basic Message
    • Connection between Springboot and RabbitMQ
    • Create core component
    • Create RabbitMQProducer
    • Create REST API to send message
    • create RabbitMQConsumer
  • Springboot and RabbitMQ Json Message
    • Create Json object
    • add config
    • Produce json message
    • Create API to send json object
    • Consum json message

What is RabbitMQ?

RabbitMQ Core concept

RabbitMQ Architecture

Install and setup RabbitMQ using Docker

# notice: select 3.11.15-management, it will have web management web page
docker pull rabbitmq:3.11.15-management
docker run --rm  -it -p 15672:15672 -p 5672:5672 rabbitmq:3.11.0

Explore RabbitMQ using management UI

when we first login, username is guest and password is guest. Then we do some common operations in the dashboard.

  • create exchange
    在这里插入图片描述
  • create queue
    在这里插入图片描述
  • binding exchange with queue using routing key
    在这里插入图片描述

在这里插入图片描述
After finish all the operations, we can test whether it is work here. So publish a message to exchange, if we can get message in queue, we can think it works.
在这里插入图片描述

在这里插入图片描述

Create and setup Springboot3 project in intellij

First, using spring initializr to quick create and bootstrap spring boot project.
在这里插入图片描述
Second, using intellij open the project.
在这里插入图片描述

Springboot and RabbitMQ Basic Message

Connection between Springboot and RabbitMQ

Springboot autoconfiguration for spring AMQP(RabbitMQ). We get a connection to our RabbitMQ broker on port 5672 using the default username and password of "guest".

Define these proprtties in a application.properties.

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

Create core component

  • setup queue name, exchange name and routing key name in application.properties.
spring.rabbitmq.queue_name=fan_queue
spring.rabbitmq.exchange_name=fan_exchange
spring.rabbitmq.routing_key=fan_routing_key
  • write the java code to create queue, exchange and binding.
// file path: com/fan/springbootrabbitmq/config
package com.fan.springbootrabbitmq.config;import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class RabbitMQConfig {@Value("${spring.rabbitmq.queue_name}")private String queueName;@Value("${spring.rabbitmq.exchange_name}")private String exchangeName;@Value("${spring.rabbitmq.routing_key}")private String routingKey;// spring bean for rabbitmq queue@Beanpublic Queue queue() {return new Queue(queueName);}// spring bean for rabbitmq exchange@Beanpublic TopicExchange exchange() {return new TopicExchange(exchangeName);}// binding between queue and exchange using routing key@Beanpublic Binding binding() {return BindingBuilder.bind(queue()).to(exchange()).with(routingKey);}
}
  • rerun the project and check whether there are error, if no error, it works.

Create RabbitMQProducer

// file path:  com/fan/springbootrabbitmq/publisher/RabbitMQProducer.java
package com.fan.springbootrabbitmq.publisher;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;@Service
public class RabbitMQProducer {@Value("${spring.rabbitmq.exchange_name}")private String exchangeName;@Value("${spring.rabbitmq.routing_key}")private String routingKey;// use RabbitTemplate to send the messages. it auto config for us, we just need to inject and use it.private final RabbitTemplate rabbitTemplate;private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQProducer.class);public RabbitMQProducer(RabbitTemplate rabbitTemplate) {this.rabbitTemplate = rabbitTemplate;}public void sendMessage(String message) {LOGGER.info(String.format("Message sent => %s", message));rabbitTemplate.convertAndSend(exchangeName, routingKey, message);}
}

Create REST API to send message

// file path: com/fan/springbootrabbitmq/controller/RabbitMQController.java
package com.fan.springbootrabbitmq.controller;import com.fan.springbootrabbitmq.publisher.RabbitMQProducer;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/api/v1")
public class RabbitMQController {private RabbitMQProducer producer;public RabbitMQController(RabbitMQProducer producer) {this.producer = producer;}@GetMapping("/publish")public ResponseEntity<String> publish(@RequestParam("message") String message) {producer.sendMessage(message);return ResponseEntity.ok("Message sent to rabbitmq...");}
}

how to test?

  • send api request to send message to rabbitmq: http://localhost:8080/api/v1/publish?message=xxx
  • check in the dashboard: http://localhost:15672/

create RabbitMQConsumer

// file path: com/fan/springbootrabbitmq/publisher/RabbitMQConsumer.java
package com.fan.springbootrabbitmq.publisher;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;@Service
public class RabbitMQConsumer {private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQProducer.class);@RabbitListener(queues = "${spring.rabbitmq.queue_name}")public void consum(String message) {LOGGER.info(String.format("Message received => %s", message));}}

after finish this part, rerun the project and send a request for sending message to rabbitmq, and then you can see the result in peoject like this:

[ntContainer#0-1] c.f.s.publisher.RabbitMQProducer         : Message sent => hello1
[ntContainer#0-1] c.f.s.publisher.RabbitMQProducer         : Message received => hello1

Springboot and RabbitMQ Json Message

Create Json object

// file path: com/fan/springbootrabbitmq/dto/User.java
package com.fan.springbootrabbitmq.dto;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {private Long id;private String firstName;private String lastName;
}

add config

// file path: com/fan/springbootrabbitmq/config/RabbitMQConfig.java// add this attributes to RabbitMQConfig class@Value("${spring.rabbitmq.json.queue_name}")private String queueJsonName;@Value("${spring.rabbitmq.json.routing_key}")private String routingJsonKey;// add this methods to RabbitMQConfig class@Beanpublic Queue jsonQueue() {return new Queue(queueJsonName);}@Beanpublic MessageConverter converter(){return new Jackson2JsonMessageConverter();}@Beanpublic AmqpTemplate amqpTemplate(ConnectionFactory connectionFactory){RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);rabbitTemplate.setMessageConverter(converter());return rabbitTemplate;}@Beanpublic Binding jsonBinding() {return BindingBuilder.bind(jsonQueue()).to(exchange()).with(routingJsonKey);}

Produce json message

// file path: com/fan/springbootrabbitmq/publisher/RabbitMQJsonProducer.java
package com.fan.springbootrabbitmq.publisher;import com.fan.springbootrabbitmq.dto.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;@Service
public class RabbitMQJsonProducer {@Value("${spring.rabbitmq.exchange_name}")private String exchangeName;@Value("${spring.rabbitmq.routing_key}")private String routingKey;// use RabbitTemplate to send the messages. it auto config for us, we just need to inject and use it.private final RabbitTemplate rabbitTemplate;private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQJsonProducer.class);public RabbitMQJsonProducer(RabbitTemplate rabbitTemplate) {this.rabbitTemplate = rabbitTemplate;}public void sendJsonMessage(User user) {LOGGER.info(String.format("Message sent => %s", user.toString()));rabbitTemplate.convertAndSend(exchangeName, routingKey, user);}
}

Create API to send json object

// file path: com/fan/springbootrabbitmq/publisher/RabbitMQJsonProducer.java
package com.fan.springbootrabbitmq.publisher;import com.fan.springbootrabbitmq.dto.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;@Service
public class RabbitMQJsonProducer {@Value("${spring.rabbitmq.exchange_name}")private String exchangeName;@Value("${spring.rabbitmq.json.routing_key}")private String routingJsonKey;// use RabbitTemplate to send the messages. it auto config for us, we just need to inject and use it.private final RabbitTemplate rabbitTemplate;private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQJsonProducer.class);public RabbitMQJsonProducer(RabbitTemplate rabbitTemplate) {this.rabbitTemplate = rabbitTemplate;}public void sendJsonMessage(User user) {LOGGER.info(String.format("Message sent => %s", user.toString()));rabbitTemplate.convertAndSend(exchangeName, routingJsonKey, user);}
}

Consum json message

file path: com/fan/springbootrabbitmq/publisher/RabbitMQJsonConsumer.java
package com.fan.springbootrabbitmq.publisher;import com.fan.springbootrabbitmq.dto.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;@Service
public class RabbitMQJsonConsumer {private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQProducer.class);@RabbitListener(queues = "${spring.rabbitmq.json.queue_name}")public void consum(User user) {LOGGER.info(String.format("Message received => %s", user.toString()));}}

相关文章:

Learn RabbitMQ with SpringBoot

文章目录 What is RabbitMQ?RabbitMQ Core conceptRabbitMQ ArchitectureInstall and setup RabbitMQ using DockerExplore RabbitMQ using management UICreate and setup Springboot3 project in intellijSpringboot and RabbitMQ Basic MessageConnection between Springbo…...

定时器 POSIX Timer定时器和setitimer定时器

POSIX 可移植 POSIX&#xff1a;可移植操作系统接口&#xff08;Portable Operating System Interface of UNIX&#xff0c;缩写为 POSIX 。 POSIX Timer C API 总结POSIX系统的C标准库&#xff1a; 函数描述clock_settime()通过指定Value设置clock的分辨率clock_gettime()…...

DeSD:用于3D医学图像分割的深度自蒸馏自监督学习

文章目录 DeSD: Self-Supervised Learning with Deep Self-Distillation for 3D Medical Image Segmentation摘要本文方法Deep Self-DistillationDownstream Transfer Learning 实验结果 DeSD: Self-Supervised Learning with Deep Self-Distillation for 3D Medical Image Seg…...

MySQL数据库——MySQL创建触发器(CREATE TRIGGER)

触发器是与 MySQL 数据表有关的数据库对象&#xff0c;在满足定义条件时触发&#xff0c;并执行触发器中定义的语句集合。触发器的这种特性可以协助应用在数据库端确保数据的完整性。 基本语法 在 MySQL 5.7 中&#xff0c;可以使用 CREATE TRIGGER 语句创建触发器。 语法格…...

Java实现网上人才招聘系统【附源码】

网上人才招聘系统 1、概述 3 2、系统分析 4 2.1、问题定义 4 2.2、可行性研究 4 2.2.1、可行性需求分析 4 2.2.2、数据流分析 5 2.2.3、数据字典 6 2.2.4、程序流程图 6 2.2.4、开发进度计划 6 2.3、需求分析 7 2.3.1、功能需求分析 7 2.3.2、数据需求分析 10 2.3.3、性能需求…...

jmeter接口测试项目实战详解,零基础也能学,源码框架都给你

目录 1.什么是jmeter&#xff1f; 2.jmeter能做什么&#xff1f; 3.jmeter环境搭建 3.1前提&#xff1a; 3.2jmeter下载&#xff1a; 3.3jmeter环境搭建&#xff1a; 3.3.1mac当中jmeter环境搭建&#xff1a; 3.4jmeter基本配置 3.4.1.切换语言 3.4.2.安装插件 4.jmet…...

MySQL中去重 distinct 和 group by 是如何去重的

1&#xff1a;测试数据 CREATE TABLE student (stu_no VARCHAR(40) NOT NULL,name VARCHAR(100) NOT NULL );insert into student values(1,name1); insert into student values(2,name2); insert into student values(3,name1); insert into student values(4,name2); i…...

在职读研是理想还是情怀?你想要的都将在社科大能源管理硕士项目实现

在职读研是理想还是情怀呢&#xff0c;每个读研人的想法不同&#xff0c;原因也有所不同。但选择在职继续攻读硕士学位的群体也有着共同点&#xff0c;他们都是想拥有高学历&#xff0c;拥有高目标的一群人。探寻新的起点和终点是他们想所要追求的。不管读研的初心是什么&#…...

携手共建数字钢铁,Hightopo亮相第三届钢铁展洽会

4 月 26 日备受期待的第三届钢铁展洽会在日照盛大召开。图扑软件作为智慧钢铁行业领先的 2D 和 3D 图形界面可视化解决方案提供商&#xff0c;受邀参与此次展会。 图扑软件携智慧钢铁三维可视化监控体系亮相“钢铁展洽会”&#xff0c;向众多钢铁企业展示了一系列图扑 HT 数字…...

Leetcode2383. 赢得比赛需要的最少训练时长

Every day a Leetcode 题目来源&#xff1a;2383. 赢得比赛需要的最少训练时长 解法1&#xff1a;模拟 可以分开考虑在比赛开始前&#xff0c;需要最少增加的精力和经验数量。 每次遇到一个对手&#xff0c;当前精力值都需要严格大于当前对手&#xff0c;否则需要增加精力值…...

js代码执行过程、调用栈、执行上下文

参考资料 极客时间课程《浏览器工作原理与实践》 – 李兵 一、js代码执行过程 &#xff08;一&#xff09;javascript代码的执行流程 浏览器执行javascript代码的流程如下图所示&#xff1a; javascript的执行机制是&#xff1a;先编译&#xff0c;再执行。在编译阶段生成了…...

互联网摸鱼日报(2023-05-12)

互联网摸鱼日报&#xff08;2023-05-12&#xff09; InfoQ 热门话题 建设和改进持续业务交付能力&#xff5c; BizDevOps 公开课 一部手机就可运行&#xff0c;精通Python等20种语言&#xff01;谷歌终于能与OpenAI 打擂台了&#xff0c;全新PaLM 2比肩GPT-4 蚂蚁数科开发者…...

【Python从入门到实践3.1】扑克发牌知识点(range函数,def函数,else语句配合使用,random库,列表推导式)

扑克发牌知识点 range函数def函数else语句配合使用&#xff1a;random库列表推导式 本篇博文需要特别感谢"Python从入门到精通"课程中一位同学对扑克发牌程序做出的知识点分析,本博文的内容大多也是从这位同学的分析而来. range函数 Range()函数&#xff1a; *返回一…...

Spring Cloud第二季--Spring Cloud Bus

文章目录 Spring Clud Bus什么是总线基本原理 牛刀小试 Spring Clud Bus 在Spring Cloud学习–配置中心&#xff08;Config&#xff09;中实现了集中管理微服务配置、不同环境不同配置、运行期间也可动态调整、配置修改后可以自动更新的需求&#xff0c;但同时也有一个弊端&am…...

Unittest自动化测试之unittestunittest_生成测试报告

unittest_生成测试报告 测试报告为测试结果的统计即展示&#xff0c;是自动化测试不可或缺的一部分&#xff0c;利用unittest 可以生成测试报告 方式一、使用第三方 HTMLTestRunner 执行测试用例集&#xff0c;生成网页版测试报告&#xff08;推荐&#xff09; HTMLTestRunn…...

一个查询IP地理信息和CDN提供商的离线终端工具

Nali 功能 支持多种数据库 纯真 IPv4 离线数据库ZX IPv6 离线数据库Geoip2 城市数据库 (可选)IPIP 数据库 (可选)ip2region 数据库 (可选)DB-IP 数据库 (可选)IP2Location DB3 LITE 数据库 (可选) CDN 服务提供商查询支持管道处理支持交互式查询同时支持IPv4和IPv6支持多语言…...

RflySim平台使用篇 | Rflysim3D软件使用系列教程(二)

导读: RflySim3D&#xff08;支持体验版&#xff09;和RflySimUE5&#xff08;支持完整版&#xff09;为本平台核心三维显示软件&#xff0c; 分别基于UE4 和UE5 引擎开发&#xff0c;具备高逼真虚拟现实显示效果。本视频主要讲解了如何将自定义的三维场景如何加载到RflySim3D…...

2023 年第五届河南省 CCPC 大学生程序设计竞赛

题目地址 题目PDF地址 题解地址 Problem A. 小水獭游河南 ∣ a ∣ ≤ ∣ Σ ∣ 26 &#xff0c;暴力枚举 a 判断 b 是否为是回文串即可&#xff0c;时间复杂度 O ( ∣ Σ ∣ ∣ s ∣ ) 。 |a| ≤ |Σ| 26&#xff0c;暴力枚举 a 判断 b 是否为是回文串即可&#xff0c;时间…...

nginx liunx最新版本安装flask部署

一、nginx安装 1.进入Nginx官网的资源下载页&#xff1a;http://nginx.org/en/download.html 2.下载nginx-1.22.1.tar.gz&#xff0c; 3解压&#xff1a; tar -zxvf nginx-1.22.1.tar.gz解压完成后会在当前目录下得到一个新的nginx文件夹 4.终端进入nginx文件夹目录&#x…...

热图 -- pheatmap or ggplot2

文章目录 brief数据准备 pheatmap实例最朴素的方式数据缩放取消聚类更改每个小方格的大小聚类以及聚类方式和参数修改热图呈现的颜色修改legend ggplot2实例ggplot2实例变式添加 group bar做成dotplot pheatmap 多图组合问题 brief 这里主要记录了pheatmap 以及 ggplot2实现热…...

铭豹扩展坞 USB转网口 突然无法识别解决方法

当 USB 转网口扩展坞在一台笔记本上无法识别,但在其他电脑上正常工作时,问题通常出在笔记本自身或其与扩展坞的兼容性上。以下是系统化的定位思路和排查步骤,帮助你快速找到故障原因: 背景: 一个M-pard(铭豹)扩展坞的网卡突然无法识别了,扩展出来的三个USB接口正常。…...

synchronized 学习

学习源&#xff1a; https://www.bilibili.com/video/BV1aJ411V763?spm_id_from333.788.videopod.episodes&vd_source32e1c41a9370911ab06d12fbc36c4ebc 1.应用场景 不超卖&#xff0c;也要考虑性能问题&#xff08;场景&#xff09; 2.常见面试问题&#xff1a; sync出…...

智慧工地云平台源码,基于微服务架构+Java+Spring Cloud +UniApp +MySql

智慧工地管理云平台系统&#xff0c;智慧工地全套源码&#xff0c;java版智慧工地源码&#xff0c;支持PC端、大屏端、移动端。 智慧工地聚焦建筑行业的市场需求&#xff0c;提供“平台网络终端”的整体解决方案&#xff0c;提供劳务管理、视频管理、智能监测、绿色施工、安全管…...

遍历 Map 类型集合的方法汇总

1 方法一 先用方法 keySet() 获取集合中的所有键。再通过 gey(key) 方法用对应键获取值 import java.util.HashMap; import java.util.Set;public class Test {public static void main(String[] args) {HashMap hashMap new HashMap();hashMap.put("语文",99);has…...

线程同步:确保多线程程序的安全与高效!

全文目录&#xff1a; 开篇语前序前言第一部分&#xff1a;线程同步的概念与问题1.1 线程同步的概念1.2 线程同步的问题1.3 线程同步的解决方案 第二部分&#xff1a;synchronized关键字的使用2.1 使用 synchronized修饰方法2.2 使用 synchronized修饰代码块 第三部分&#xff…...

(二)TensorRT-LLM | 模型导出(v0.20.0rc3)

0. 概述 上一节 对安装和使用有个基本介绍。根据这个 issue 的描述&#xff0c;后续 TensorRT-LLM 团队可能更专注于更新和维护 pytorch backend。但 tensorrt backend 作为先前一直开发的工作&#xff0c;其中包含了大量可以学习的地方。本文主要看看它导出模型的部分&#x…...

(二)原型模式

原型的功能是将一个已经存在的对象作为源目标,其余对象都是通过这个源目标创建。发挥复制的作用就是原型模式的核心思想。 一、源型模式的定义 原型模式是指第二次创建对象可以通过复制已经存在的原型对象来实现,忽略对象创建过程中的其它细节。 📌 核心特点: 避免重复初…...

Module Federation 和 Native Federation 的比较

前言 Module Federation 是 Webpack 5 引入的微前端架构方案&#xff0c;允许不同独立构建的应用在运行时动态共享模块。 Native Federation 是 Angular 官方基于 Module Federation 理念实现的专为 Angular 优化的微前端方案。 概念解析 Module Federation (模块联邦) Modul…...

LLM基础1_语言模型如何处理文本

基于GitHub项目&#xff1a;https://github.com/datawhalechina/llms-from-scratch-cn 工具介绍 tiktoken&#xff1a;OpenAI开发的专业"分词器" torch&#xff1a;Facebook开发的强力计算引擎&#xff0c;相当于超级计算器 理解词嵌入&#xff1a;给词语画"…...

UR 协作机器人「三剑客」:精密轻量担当(UR7e)、全能协作主力(UR12e)、重型任务专家(UR15)

UR协作机器人正以其卓越性能在现代制造业自动化中扮演重要角色。UR7e、UR12e和UR15通过创新技术和精准设计满足了不同行业的多样化需求。其中&#xff0c;UR15以其速度、精度及人工智能准备能力成为自动化领域的重要突破。UR7e和UR12e则在负载规格和市场定位上不断优化&#xf…...