Learn RabbitMQ with SpringBoot

news2024/10/5 8:15:11

文章目录

  • 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
    @Bean
    public Queue queue() {
        return new Queue(queueName);
    }

    // spring bean for rabbitmq exchange
    @Bean
    public TopicExchange exchange() {
        return new TopicExchange(exchangeName);
    }

    // binding between queue and exchange using routing key
    @Bean
    public 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

    @Bean
    public Queue jsonQueue() {
        return new Queue(queueJsonName);
    }

    @Bean
    public MessageConverter converter(){
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public AmqpTemplate amqpTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(converter());
        return rabbitTemplate;
    }

    @Bean
    public 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()));
    }

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/516184.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【C++ 入坑指南】(03)Hello World

大概每个程序猿的第一个程序都是 Hello World , 这是梦开始的地方。本文是C 入坑指南的第三篇&#xff0c;让我们从最经典的 Hello World 开始。 看代码 #include <iostream>using namespace std;int main() {cout << "Hello, world!" << endl;r…

Linkage Mapper 构建区域生态系统地图的指南

✅创作者&#xff1a;陈书予 &#x1f389;个人主页&#xff1a;陈书予的个人主页 &#x1f341;陈书予的个人社区&#xff0c;欢迎你的加入: 陈书予的社区 &#x1f31f;专栏地址: Linkage Mapper解密数字世界链接 文章目录 引言一、简介二、确定地图范围三、收集和整理空间数…

算法修炼之练气篇——练气一层

博主&#xff1a;命运之光 专栏&#xff1a;算法修炼之练气篇 题目1157: 亲和数 这道题很简单&#xff0c;我写的也很简单&#xff0c;看一眼就懂 题目描述 古希腊数学家毕达哥拉斯在自然数研究中发现&#xff0c;220的所有真约数(即不是自身的约数)之和为&#xff1a; 1245…

【MyBatis】 MyBatis 动态SQL使用及原理

文章目录 前言1. 动态SQL概述2. if标签3. choose、when和otherwise标签4. trim标签5. set标签和where标签6. foreach7. bind8. 动态SQL解析原理总结 前言 MyBatis 是一个优秀的持久层框架&#xff0c;它提供了丰富的 SQL 映射功能&#xff0c;可以让我们通过 XML 或注解方式来…

@SpringBootApplication深入剖析

如下图 SpringBootApplication是springboot项目启动类的注解&#xff0c;也是程序的入口,本文就是具体解析一下这个注解到底做了什么 一.SpringBootApplication的构成 1.这个注解是一个组合注解&#xff0c;他是有三个注解合成的&#xff0c;对应图中的123步&#xff0c;而这三…

新的勒索软件加密自身以逃避防病毒

一种名为 Cactus 的新型勒索软件一直在利用 VPN 设备中的漏洞对“大型商业实体”的网络进行初始访问。 Cactus 勒索软件行动至少从 3 月开始就一直活跃&#xff0c;并正在寻求受害者的大笔支出。 虽然新的威胁参与者采用了勒索软件攻击中常见的策略——文件加密和数据窃取——…

大数据Doris(十七):Random Distribution和复合分区使用场景

文章目录 Random Distribution和复合分区使用场景 一、Random Distribution 二、复合分区使用场景 Random Distribution和复合分区使用场景 一、Random Distribution 如果 OLAP 表没有更新类型的字段&#xff0c;将表的数据分桶模式设置为 RANDOM&#xff0c;则可以避免严…

架构设计之需求分析

大家好&#xff0c;我是易安。 设计架构的第一步是需求分析。那么&#xff0c;为什么要做需求分析&#xff1f;如何做好需求分析&#xff1f;今天我们一起聊一聊需求分析这件事儿 为什么要做需求分析 为何要做需求分析&#xff1f; 首先&#xff0c;当然是因为我们做软件本身就…

迭代器失效问题,以及解决方法。

迭代器的主要作用就是让算法能够不用关心底层数据结构&#xff0c;其底层实际就是一个指针&#xff0c;或者是对指针进行了封装&#xff0c;比如&#xff1a;vector的迭代器就是原生态指针T* 。因此迭代器失效&#xff0c;实际就是迭代器底层对应指针所指向的空间被销毁了&…

【小沐学Python】Python实现Web服务器(Flask+Vue+node.js,web单页增删改查)

文章目录 1、简介1.1 flask1.2 vue 2、开发2.1 新建flask项目2.2 安装flask库2.3 新建flask的主脚本2.4 新建Vue项目2.5 安装vue项目依赖项2.6 新增组件Ping.vue2.7 Ping.vue增加HTTP请求2.8 美化vue前端页面2.9 新增组件Books.vue2.10 flask增加路由Books2.11 Books.vue增加HT…

什么是ChatGPT?怎么用?

最近全网爆火的黑科技&#xff0c;叫做chatGPT。ChatGPT声称&#xff0c;它的AI对话模型能在大范围、细粒度问题上给出普遍准确的答案。简单地说&#xff0c;AI对话模型可以达到基本不犯错误的水平了。那么到底这个ChatGPT是什么&#xff1f;怎么用&#xff1f;本篇文章就来带大…

算法修炼之练气篇——练气二层

博主&#xff1a;命运之光 专栏&#xff1a;算法修炼之练气篇 题目 1084: 用筛法求之N内的素数 题目描述 用筛法求之N内的素数。 输入格式 N 输出格式 0&#xff5e;N的素数 样例输入 100 样例输出 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 …

学系统集成项目管理工程师(中项)系列21a_整体管理(上)

1. 含义 1.1. 包括为识别、定义、组合、统一和协调各项目管理过程组的各种过程和活动而开展的工作&#xff0c;是项目管理中一项综合性和全局性的管理工作 2. 项目经理是整合者 2.1. 【21上选33】 2.1.1. 【19上选37】 2.1.2. 【22上选33】 2.2. 通过与项目干系人主动、全…

shell脚本(磁盘空间、服务状态)

1、判断当前磁盘剩余空间是否有20G&#xff0c;如果小于20G&#xff0c;则将报警邮件发送给管理员&#xff0c;每天检查一次磁盘剩余空间。 第一步&#xff1a;创建脚本名为shell1.sh如下&#xff1a; vim shell1.sh 第二步&#xff1a;做计划在shell1文件中&#xff0c;命令…

Kyligence Zen 简直就是一站式指标平台的天花板

一、Kyligence Zen是什么&#xff1f; 1、Kyligence Zen是做啥的&#xff1f; Kyligence Zen是一款指标分析和管理的工具&#xff0c;是基于 Kyligence 核心 OLAP 能力打造&#xff0c;Kyligence Zen 提供集业务模型、指标管理、指标加工、数据服务于一体的一站式服务&#x…

孙溟㠭20余载春秋,4000多方印章,这双质朴的手有多么倔强的生命力

作品的背后往往折射出艺术家人生的广度和厚度。 先锋篆刻、书画艺术家孙溟㠭&#xff0c; 上世纪90年代开始接触篆刻&#xff0c; 至今&#xff0c;20载有余&#xff0c;积累了4000多方篆刻作品。 在他创作纪念吴品超院士的作品《药生尘》时&#xff0c; 我们拍到了艺术家…

高级Web题库

高级Web题库 For ZPT 声明 一切开发旨在学习&#xff0c;请勿用于非法用途 by rick rick 关注 永雏塔菲喵 永雏塔菲喵 选择题 第1题 知识点&#xff1a;CSS 题目&#xff1a;设置text-decoration属性的删除线的值为&#xff08; &#xff09;。 选项&#xff1a; A underlin…

固定翼无人机培训第二周总结——多轴和起降

博主学的III类固定翼垂直起降无人机&#xff0c;起降采用多旋翼&#xff08;下图中红框就是旋翼&#xff09;&#xff0c;巡航采用固定翼。 理论大部分也是多旋翼&#xff0c;多轴旋翼无人机是指三个旋翼轴及以上的特殊直升机&#xff0c;多旋翼无人机靠旋翼速度和方向来控制无…

代码随想录算法训练营第三十八天 | 动态规划基础流程

动态规划理论基础 代码随想录 (programmercarl.com) 如果某一问题有很多重叠子问题&#xff0c;使用动态规划是最有效的。 所以动态规划中每一个状态一定是由上一个状态推导出来的&#xff0c;这一点就区分于贪心&#xff0c;贪心没有状态推导&#xff0c;而是从局部直接选最…

Java结合POI框架实现Excel导入

Java结合POI框架实现Excel导入 一、流程概念二、conroller中的方法三、导入成功 一、流程概念 我们需要把excel通过上传得方式导入数据库&#xff0c;需要以下几个步骤 将excel上传到服务器指定文件夹内并重命名&#xff08;upload&#xff09;获取到文件公共路径和别名路径将…