Spring Boot集成RabbitMQ快速入门Demo

1.什么是RabbitMQ?

RabbitMQ是一款使用Erlang语言开发的,基于AMQP协议的消息中间件,作为一款优秀的消息系统,RabbitMQ有高并发、可扩展等优势,并适用于大型系统中各个模块之间的通信。

RabbitMQ的特点为:

  • 持久化、传输确认、发布确认等功能保证消息可靠

  • 支持多种消息分发模式,处理更加灵活

  • 提供可视化管理界面,使用方便

  • 支持集群部署,保证服务高可用

2.RabbitMQ环境搭建

version: '3'
services:
  rabbitmq:
    image: registry.cn-hangzhou.aliyuncs.com/zhengqing/rabbitmq:3.7.8-management        # 原镜像`rabbitmq:3.7.8-management` 【 注:该版本包含了web控制页面 】
    container_name: rabbitmq            # 容器名为'rabbitmq'
    hostname: my-rabbit
    restart: unless-stopped                                       # 指定容器退出后的重启策略为始终重启,但是不考虑在Docker守护进程启动时就已经停止了的容器
    environment:                        # 设置环境变量,相当于docker run命令中的-e
      TZ: Asia/Shanghai
      LANG: en_US.UTF-8
      RABBITMQ_DEFAULT_VHOST: my_vhost  # 主机名
      RABBITMQ_DEFAULT_USER: admin      # 登录账号
      RABBITMQ_DEFAULT_PASS: admin      # 登录密码
    volumes: # 数据卷挂载路径设置,将本机目录映射到容器目录
      - "./rabbitmq/data:/var/lib/rabbitmq"
    ports:                              # 映射端口
      - "5672:5672"
      - "15672:15672"

运行

docker-compose -f docker-compose-rabbitmq.yml -p rabbitmq up -d

web管理端:http://127.0.0.1:15672 登录账号密码:admin/admin

27a7e34328fda7e39066d77e99a7d4a8.png

3.代码工程

实验目的:实现通过rabbitmq发送和接收消息

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>


    <artifactId>rabbitmq</artifactId>


    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>


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


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

application.properties

server.port=8088
  #rabbitmq
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin
spring.rabbitmq.virtual-host=my_vahost

config

简单使用

package com.et.rabbitmq.config;




import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;




@Configuration
public class RabbitConfig {


    @Bean
    public Queue Queue() {
        return new Queue("hello");
    }
}

topic 是RabbitMQ中最灵活的一种方式,可以根据routing_key自由的绑定不同的队列 首先对topic规则配置,这里使用两个队列来测试

package com.et.rabbitmq.config;


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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class TopicRabbitConfig {


   public final static String TOPIC_ONE = "topic.one";
   public final static String TOPIC_TWO = "topic.two";
   public final static String TOPIC_EXCHANGE = "topicExchange";


   @Bean
   public Queue queue_one(){
      return new Queue(TOPIC_ONE);
   }


   @Bean
   public Queue queue_two(){
      return new Queue(TOPIC_TWO);
   }


   @Bean
   TopicExchange exchange(){
      return new TopicExchange(TOPIC_EXCHANGE);
   }


   @Bean
   Binding bindingExchangeOne(Queue queue_one, TopicExchange exchange){
      return BindingBuilder.bind(queue_one).to(exchange).with("topic.one");
   }


   @Bean
   Binding bindingExchangeTwo(Queue queue_two, TopicExchange exchange){
      //# 表示零个或多个词
      //* 表示一个词
      return BindingBuilder.bind(queue_two).to(exchange).with("topic.#");
   }


}

Fanout 就是我们熟悉的广播模式或者订阅模式,给Fanout交换机发送消息,绑定了这个交换机的所有队列都收到这个消息。

package com.et.rabbitmq.config;


import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class FanoutRabbitConfig {


    @Bean
    public Queue AMessage() {
        return new Queue("fanout.A");
    }


    @Bean
    public Queue BMessage() {
        return new Queue("fanout.B");
    }


    @Bean
    public Queue CMessage() {
        return new Queue("fanout.C");
    }


    @Bean
    FanoutExchange fanoutExchange() {
        return new FanoutExchange("fanoutExchange");
    }


    @Bean
    Binding bindingExchangeA(Queue AMessage, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(AMessage).to(fanoutExchange);
    }


    @Bean
    Binding bindingExchangeB(Queue BMessage, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(BMessage).to(fanoutExchange);
    }


    @Bean
    Binding bindingExchangeC(Queue CMessage, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(CMessage).to(fanoutExchange);
    }


}

receiver

package com.et.rabbitmq.receiver;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class HelloReceiver {




    @RabbitListener(queues = "hello")
    public void process(String hello) {
        System.out.println("Receiver  : " + hello);
    }


    @RabbitListener(queues = {"topic.one"})
    public void receiveTopic1(@Payload String fileBody) {
        log.info("topic1:" + fileBody);
    }


    @RabbitListener(queues = {"topic.two"})
    public void receiveTopic2(@Payload String fileBody) {
        log.info("topic2:" + fileBody);
    }
    @RabbitListener(queues = {"fanout.A"})
    public void fanoutA(@Payload String fileBody) {
        log.info("fanoutA:" + fileBody);
    }


    @RabbitListener(queues = {"fanout.B"})
    public void fanoutB(@Payload String fileBody) {
        log.info("fanoutB:" + fileBody);
    }
    @RabbitListener(queues = {"fanout.C"})
    public void fanoutC(@Payload String fileBody) {
        log.info("fanoutC:" + fileBody);
    }
}

sender

package com.et.rabbitmq.sender;


import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.util.Date;
@Component
public class HelloSender {


   @Autowired
   private AmqpTemplate rabbitTemplate;


   public void send() {
      String context = "hello " + new Date();
      System.out.println("Sender : " + context);
      this.rabbitTemplate.convertAndSend("hello", context);
   }


}
package com.et.rabbitmq.sender;


import com.et.rabbitmq.config.TopicRabbitConfig;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class TopicSender {


   @Autowired
   private AmqpTemplate rabbitTemplate;


   //两个消息接受者都可以收到
   public void send_one() {
      String context = "Hi, I am message one";
      System.out.println("Sender : " + context);
      this.rabbitTemplate.convertAndSend(TopicRabbitConfig.TOPIC_EXCHANGE,"topic.one",context);
   }




   //只有TopicReceiverTwo都可以收到
   public void send_two() {
      String context = "Hi, I am message two";
      System.out.println("Sender : " + context);
      this.rabbitTemplate.convertAndSend(TopicRabbitConfig.TOPIC_EXCHANGE,"topic.two",context);
   }


}

DemoApplication.java

package com.et.quartz;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class DemoApplication {


   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

  • https://github.com/Harries/springboot-demo

4.测试

简单使用

@Test
public void hello() throws Exception {
    helloSender.send();
    Thread.sleep(50000);
}

Topic Exchange

@Test
public void topicOne() throws Exception {
    topicSender.send_one();
    Thread.sleep(50000);
}
@Test
public void topicTwo() throws Exception {
    topicSender.send_two();
    Thread.sleep(50000);
}

Fanout Exchange

@Test
public void sendFanout() throws InterruptedException {
    String context = "hi, fanout msg ";
    System.out.println("Sender : " + context);
    this.rabbitTemplate.convertAndSend("fanoutExchange","", context);
    Thread.sleep(50000);
}

5.参考连接

  • https://www.rabbitmq.com/

  • https://spring.io/projects/spring-amqp

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

微信小程序按钮点击时的样式hover-class=“hover“

小程序的button组件很好用&#xff0c;按钮点击的时候会显示点击状态&#xff0c;默认的就是颜色加深 但是我们改变了button的背景色之后&#xff0c;就看不出点击效果了&#xff0c;解决起来也很简单 关键代码就是小程序的 hover-class 属性&#xff0c;需要注意的是&#xff…

Mysql(数据库)知识详解【6】~{锁,架构}

数据库锁和架构是两个不同的概念&#xff0c;但它们都与数据库管理系统&#xff08;DBMS&#xff09;的性能和并发控制有关。 数据库锁&#xff1a; 数据库锁是一种同步机制&#xff0c;用于控制多个事务对共享资源的访问。锁可以确保数据的一致性和完整性&#xff0c;防止多个…

AI 重写人类DNA,开源基因编辑器问世;安卓版Gemini新增多项功能

&#x1f989; AI新闻 &#x1f680; AI 重写人类DNA&#xff0c;开源基因编辑器问世 摘要&#xff1a;初创公司 Profluent 最新宣布&#xff0c;开发出世界首个完全由 AI 设计的基因编辑器&#xff0c;并成功应用于人类细胞 DNA&#xff0c;这一技术可谓是分子生物学的一大突…

【stomp 实战】spring websocket源码分析之握手请求的处理

上一节【搭建一套websocket推送平台】我们通过一个项目&#xff0c;实现了一套推送平台。由于spring框架对于websocket的支持和stomp协议的良好封装&#xff0c;我们很容易地就实现了websocket的消息推送功能。虽然搭建这么一套推送系统不难&#xff0c;但是如果不了解其底层原…

Linux中手工创建一个用户

当我们需要新创建一个用户时&#xff0c;有两种方法 1.使用命令添加用户 2.去配置文件里面添加用户 1&#xff0c;使用useradd命令&#xff1a; [rootlocalhost /]# useradd tmg 然后给它设置一个密码 [rootlocalhost etc]# passwd tmg Changing password for user tmg. N…

linux 系统文件目录颜色及特殊权限对应的颜色

什么决定文件目录的颜色和背景&#xff1f; 颜色 说明 栗子 权限白色表示普通文件 蓝色表示目录 绿色表示可执行文件 浅蓝色链接文件 黄色表示设备文件 红色 表示压缩文件 红色闪烁表示链接的文件有问题 灰色 表示其它文件 可以用字符表示文件的类型&am…

新风口下的必应bing国内广告投放该怎么做?

必应Bing作为全球搜索引擎市场的重要参与者&#xff0c;正逐渐显现出其在国内市场的独特价值和潜力。随着互联网生态的多元化发展&#xff0c;必应Bing凭借其高质量用户群和精准投放能力&#xff0c;成为了企业寻求新增长点的新风口。 一、洞察先机&#xff0c;精准定位市场 …

【Flink入门修炼】2-3 Flink Checkpoint 原理机制

如果让你来做一个有状态流式应用的故障恢复&#xff0c;你会如何来做呢&#xff1f; 单机和多机会遇到什么不同的问题&#xff1f; Flink Checkpoint 是做什么用的&#xff1f;原理是什么&#xff1f; 一、什么是 Checkpoint&#xff1f; Checkpoint 是对当前运行状态的完整记…

YOLOv8+PyQt5输电线路缺陷检测(目前最全面的类别检测,可以从图像、视频和摄像头三种路径检测)

1.效果视频&#xff1a;YOLOv8PyQt5输电线路缺陷检测&#xff08;目前最全面的类别检测&#xff0c;可以从图像、视频和摄像头三种路径检测&#xff09;_哔哩哔哩_bilibili 资源包含可视化的输电线路缺陷检测系统&#xff0c;可识别图片和视频当中出现的五类常见的输电线路缺陷…

web前端学习笔记2

2. 网页穿上美丽外衣 2.1 什么是CSS CSS (Cascading Style Sheets,层叠样式表),是一种用来为结构化文档(如 HTML 文档或 XML 应用)添加样式(字体、间距和颜色等)的计算机语言,CSS 文件扩展名为 .css。 CSS样式包括对字体、颜色、边距、高度、宽度、背景图片、网页定位…

4.8 Python dict字典

Python dict字典详解 Python字典&#xff08;dict&#xff09;是一种无序的、可变的序列&#xff0c;它的元素以“键值对&#xff08;key-value&#xff09;”的形式存储。相对地&#xff0c;列表&#xff08;list&#xff09;和元组&#xff08;tuple&#xff09;都是有序的序…

Python中ArcPy按照分幅条带与成像日期拼接每个8天间隔内的遥感影像

本文介绍基于Python中的ArcPy模块&#xff0c;将大量遥感影像文件按照分幅条带编号与成像时间加以分组&#xff0c;并将同一分幅的遥感影像加以每个8天时间间隔内的镶嵌拼接的方法。 首先&#xff0c;来看一下本文具体的需求。我们现有一个文件夹&#xff0c;其中含有大量的.ti…

配置有效的防爬虫技术保护网站

本文主要介绍了防爬虫的概念、目的以及一些有效的防爬虫手段。防爬虫是指网站采取各种技术手段阻止爬虫程序对其数据进行抓取的过程。为了保护网站的数据和内容的安全性&#xff0c;防止经济损失和恶意竞争&#xff0c;以及减轻服务器负载&#xff0c;网站需要采取防爬虫机制。…

NIKKE胜利女神妮姬1.5周年(PC)怎么注册?账号注册教程一看就懂

游戏的世界观了一些轻科幻、末世和废土背景&#xff0c;剧情中也探讨了一些深刻的主题&#xff0c;比如NIKKE的人权问题。虽然整体剧情表现得连贯&#xff0c;但本质上有一些俗套情节&#xff0c;特别是在序章的玛丽安之死后&#xff0c;剧情逐渐失去了原有的紧张感&#xff0c…

那些你不知道的数据库知识:行式存储和列式存储

前几天听课&#xff0c;听到老师讲数据列式存储。 我&#x1f64b;&#x1f3fb;‍♀️&#xff1a;等等&#xff0c;what&#xff0c;什么列式存储&#xff0c;数据一行一行的展示&#xff0c;然后一行一行的存在数据库里面不就好了&#xff0c;什么叫做列式存储&#xff0c;…

rust中结构体的属性默认是不能修改的,要想修改可以有两种方式

Rust中结构体里面的属性默认是不支持修改的&#xff0c;而且默认不是pub的&#xff0c;要想修改的话&#xff0c;有两种方式&#xff0c;我以为和python里面的类似呢&#xff0c;但是还是需要一点技术含量的。如果想在引到外部修改&#xff0c;需要声明pub&#xff0c;如果想在…

专利视角下的量子竞赛:《2024全球专利格局白皮书》

2024年1月&#xff0c;欧洲量子产业联盟&#xff08;QuIC&#xff09;发布了题为《全球量子技术专利格局描述》的综合白皮书。 该文件以透明的视角展示了当今的知识产权格局&#xff0c;包括知识产权持有人的地理分布。该文件由 QuIC 知识产权&#xff08;IP&#xff09;与贸易…

【C++】图的存储 -- 邻接表

目录 邻接表的创建使用dfs遍历图dfs遍历图的递归思想 邻接表的创建 #include <iostream> using namespace std; #include <vector>struct edge//创建边集类型 {int v;//出边int w;//权值 }; const int N 100010;//顶点数量 vector<edge> e[N];//邻接表int m…

淘宝新店有流量扶持吗

淘宝新店有流量扶持 淘宝新店需要做些推广提高店铺权重 淘宝新店用3an推客做推广比较好 3an推客是给商家提供的营销工具&#xff0c;3an推客CPS推广模式由商家自主设置佣金比例&#xff0c;以及设置商品优惠券&#xff0c;激励推广者去帮助商家推广商品链接&#xff0c;按最…

初步认识泛型

文章目录 泛型的编译擦除机制 泛型的上界泛型方法 泛型的编译 擦除机制 泛型到底是怎么编译的&#xff1f;这个问题&#xff0c;也是曾经的一个面试问题。泛型本质是非常难的语法 通过命令&#xff1a;javap -c 查看字节码文件&#xff0c;所有的T都是Object。 在编译的过程当…
最新文章