Spring Boot集成RabbitMQ是现在主流的操作RabbitMQ的方式。

官方文档:https://docs.spring.io/spring-amqp/docs/current/reference/html/

  1. 引入依赖。

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>
  2. 添加配置。

    spring:
    rabbitmq:
    addresses: 127.0.0.1
    username: admin
    password: admin
    virtual-host: /test
  3. 配置类。

    import org.springframework.amqp.core.Binding;
    import org.springframework.amqp.core.BindingBuilder;
    import org.springframework.amqp.core.Exchange;
    import org.springframework.amqp.core.ExchangeBuilder;
    import org.springframework.amqp.core.Queue;
    import org.springframework.amqp.core.QueueBuilder;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration; /**
    * RabbitMQ配置类
    */
    @Configuration
    public class RabbitMqConfig { /**
    * 定义交换机,可以很多个
    * @return 交换机对象
    */
    @Bean("directExchange")
    public Exchange exchange(){
    return ExchangeBuilder.directExchange("amq.direct").build();
    } /**
    * 定义消息队列
    * @return 消息队列对象
    */
    @Bean("testQueue")
    public Queue queue(){
    return QueueBuilder
    // 非持久化类型
    .nonDurable("test_springboot")
    .build();
    } /**
    * 定义绑定关系
    * @return 绑定关系
    */
    @Bean
    public Binding binding(@Qualifier("directExchange") Exchange exchange,
    @Qualifier("testQueue") Queue queue){
    // 将定义的交换机和队列进行绑定
    return BindingBuilder
    // 绑定队列
    .bind(queue)
    // 到交换机
    .to(exchange)
    // 使用自定义的routingKey
    .with("test_springboot_key")
    // 不设置参数
    .noargs();
    }
    }

普通消费

  1. 实现生产者。

    import org.junit.jupiter.api.Test;
    import org.springframework.amqp.rabbit.core.RabbitTemplate;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest
    class RabbitMqSpringBootTests { /**
    * RabbitTemplate封装了大量的RabbitMQ操作,已经由Starter提供,因此直接注入使用即可
    */
    @Autowired
    private RabbitTemplate rabbitTemplate; /**
    * 生产者
    */
    @Test
    void producer() { /*
    发送消息
    参数 1:指定交换机。
    参数 2:指定路由标识。
    参数 3:消息内容。
    */
    rabbitTemplate.convertAndSend("amq.direct", "test_springboot_key", "Hello World!");
    } }

    运行代码后,查看可视化界面,可以看到创建了一个新的队列:

    绑定关系也已经建立:

  2. 实现消费者。

    消费者实际上就是一直等待消息然后进行处理的角色,这里只需要创建一个监听器就行了,它会一直等待消息到来然后再进行处理:

    import org.springframework.amqp.core.Message;
    import org.springframework.amqp.rabbit.annotation.RabbitListener;
    import org.springframework.stereotype.Component; /**
    * 直连队列监听器
    * @author CodeSail
    */
    @Component
    public class DirectListener { /**
    * 定义此方法为队列test_springboot的监听器,一旦监听到新的消息,就会接受并处理
    * @param message 消息内容
    */
    @RabbitListener(queues = "test_springboot")
    public void customer(Message message){
    System.out.println(new String(message.getBody()));
    }
    }
  3. 启动服务。

    可以看到,成功消费了消息。

消费并反馈

如果需要确保消息能够被消费者接受并处理,然后得到消费者的反馈,也是可以的。

  1. 定义生产者。

    import org.junit.jupiter.api.Test;
    import org.springframework.amqp.rabbit.core.RabbitTemplate;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest
    class RabbitMqSpringBootTests { /**
    * RabbitTemplate封装了大量的RabbitMQ操作,已经由Starter提供,因此直接注入使用即可
    */
    @Autowired
    private RabbitTemplate rabbitTemplate; /**
    * 生产者
    */
    @Test
    void producer() { // 会等待消费者消费然后返回响应结果
    Object res = rabbitTemplate.convertSendAndReceive("amq.direct", "test_springboot_key", "Hello World!");
    System.out.println("收到消费者响应:" + res);
    } }
  2. 定义生产者。

    import org.springframework.amqp.rabbit.annotation.RabbitListener;
    import org.springframework.stereotype.Component; /**
    * 直连队列监听器
    * @author CodeSail
    */
    @Component
    public class DirectListener { /**
    * 定义此方法为队列test_springboot的监听器,一旦监听到新的消息,就会接受并处理
    * @param message 消息内容
    */
    @RabbitListener(queues = "test_springboot")
    public String customer(String message){
    System.out.println("1号消息队列监听器:" + message);
    return "收到!";
    }
    }
  3. 启动生产者发送消息。

    可以看到,消费完成后接收到了反馈消息。

Json消息

  1. 引入依赖。

    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.14.2</version>
    </dependency>
  2. 定义对象。

    import lombok.Data;
    
    /**
    * 用户
    */
    @Data
    public class User { /**
    * 姓名
    */
    private String name; /**
    * 年龄
    */
    private Integer age; }
  3. 定义Bean。

    import org.springframework.amqp.core.Binding;
    import org.springframework.amqp.core.BindingBuilder;
    import org.springframework.amqp.core.Exchange;
    import org.springframework.amqp.core.ExchangeBuilder;
    import org.springframework.amqp.core.Queue;
    import org.springframework.amqp.core.QueueBuilder;
    import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration; /**
    * RabbitMQ配置类
    */
    @Configuration
    public class RabbitMqConfig { ... /**
    * 构建Json转换器
    * @return Json转换器
    */
    @Bean
    public Jackson2JsonMessageConverter jackson2JsonMessageConverter(){
    return new Jackson2JsonMessageConverter();
    }
    }
  4. 定义消费者。

    import cn.codesail.rabbitmq.entity.User;
    import org.springframework.amqp.rabbit.annotation.RabbitListener;
    import org.springframework.stereotype.Component; /**
    * 直连队列监听器
    */
    @Component
    public class DirectListener { /**
    * 指定messageConverter为创建的Bean名称
    * @param user 用户
    */
    @RabbitListener(queues = "test_springboot", messageConverter = "jackson2JsonMessageConverter")
    public void receiver(User user) {
    System.out.println(user);
    }
    }
  5. 定义生产者。

    import cn.codesail.rabbitmq.entity.User;
    import org.junit.jupiter.api.Test;
    import org.springframework.amqp.rabbit.core.RabbitTemplate;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest
    class RabbitMqSpringBootTests { /**
    * RabbitTemplate封装了大量的RabbitMQ操作,已经由Starter提供,因此直接注入使用即可
    */
    @Autowired
    private RabbitTemplate rabbitTemplate; /**
    * 生产者
    */
    @Test
    void producer() { // 发送Json消息
    User user = new User();
    user.setName("张三");
    user.setAge(18);
    rabbitTemplate.convertAndSend("amq.direct", "test_springboot_key", user);
    } }
  6. 启动生产者发送消息。

    可以看到,对象转成了Json,消费者接收到Json转为的对象。

Spring Boot操作RabbitMQ是十分方便的,也是现在的主流,后续都用这种方式演示。


  • 环境

    • JDK 17.0.6
    • Maven 3.6.3
    • SpringBoot 3.0.4
    • spring-boot-starter-amqp 3.0.4
    • jackson-databind 2.14.2

RabbitMQ 05 直连模式-Spring Boot操作的更多相关文章

  1. 使用Spring Boot操作Hive JDBC时,启动时报出错误:NoSuchMethodError: org.eclipse.jetty.servlet.ServletMapping.setDef

    使用Spring Boot操作Hive JDBC时,启动时报出错误:NoSuchMethodError: org.eclipse.jetty.servlet.ServletMapping.setDef ...

  2. MongoDB最简单的入门教程之四:使用Spring Boot操作MongoDB

    Spring Boot 是一个轻量级框架,可以完成基于 Spring 的应用程序的大部分配置工作.Spring Boot的目的是提供一组工具,以便快速构建容易配置的Spring应用程序,省去大量传统S ...

  3. Spring Boot 操作 Excel

    Excel 在日常操作中经常使用到,Spring Boot 中使用 POI 操作 Excel 本项目源码 github 下载 1 新建 Spring Boot Maven 示例工程项目 注意:本示例是 ...

  4. Java框架spring Boot学习笔记(五):Spring Boot操作MySQL数据库增、删、改、查

    在pom.xml添加一下代码,添加操作MySQL的依赖jar包. <dependency> <groupId>org.springframework.boot</grou ...

  5. Java框架spring Boot学习笔记(四):Spring Boot操作MySQL数据库

    在pom.xml添加一下代码,添加操作MySQL的依赖jar包. <dependency> <groupId>org.springframework.boot</grou ...

  6. spring boot 操作MySQL pom添加的配置

    1 在项目中的pom.xml配置文件添加依赖 <!--MySQL依赖 --> <dependency> <groupId>mysql</groupId> ...

  7. 【转】redis 消息队列发布订阅模式spring boot实现

    最近做项目的时候写到一个事件推送的场景.之前的实现方式是起job一直查询数据库,看看有没有最新的消息.这种方式非常的不优雅,反正我是不能忍,由于羡慕本身就依赖redis,刚好redis 也有消息队列的 ...

  8. spring boot实战(第十二篇)整合RabbitMQ

    前言 最近几篇文章将围绕消息中间件RabbitMQ展开,对于RabbitMQ基本概念这里不阐述,主要讲解RabbitMQ的基本用法.Java客户端API介绍.spring Boot与RabbitMQ整 ...

  9. Spring Boot (26) RabbitMQ延迟队列

    延迟消息就是指当消息被发送以后,并不想让消费者立即拿到消息,而是等待指定时间后,消费者才拿到这个消息进行消费. 延迟队列 订单业务: 在电商/点餐中,都有下单后30分钟内没有付款,就自动取消订单. 短 ...

  10. Spring Boot (25) RabbitMQ消息队列

    MQ全程(Message Queue)又名消息队列,是一种异步通讯的中间件.可以理解为邮局,发送者将消息投递到邮局,然后邮局帮我们发送给具体的接收者,具体发送过程和时间与我们无关,常见的MQ又kafk ...

随机推荐

  1. Unity3D之OnTriggerEnter和OnCollisionEnter

    OnCollisionEnter方法要求碰撞的发起方必须拥有刚体,而被碰撞方有没有刚体并不重要; OnTriggerEnter方法则对此没有要求,只需要碰撞双方有一个具有刚体即可触发,当有物体勾选is ...

  2. 【Azure 容器应用】在中国区Azure上创建的容器服务默认应用域名不全

    问题描述 在中国区Azure上,创建Container App服务,发现默认的应用程序URL只有前半段,并不是一个完整的域名.这是什么情况呢? 正常的Container App的URL格式为:< ...

  3. C++ STL 容器-array类型

    C++ STL 容器-array类型 array是C++11STL封装的数组,内存分配在栈中stack,绝对不会重新分配,随机访问 创建和初始化 // 下面的等同于int a[10]; std::ar ...

  4. Zabbix自动发现:python-json模块应用介绍

    一.JSON模块介绍 json模块是python内置的库,其主要功能是将序列化数据从文件里读取出来或者存入文件.该模块有四个方法:dump().load().dumps().loads(),其中dum ...

  5. PowerShell alias - cmd中设置别名 快捷的执行命令

    Step. 1: 发现需求 最近学nest.js发现,都是用命令创建工程文件,然后教程里面都是用的快捷命令 比如 pd = pnpm run dev pb = pnpm run build 但是我这里 ...

  6. C语言中的rand()函数实例分析

    一 前记: c语言中需要用到随机值得时候,每次都自己写,这样太浪费效率了,这次遇到了一个经典的代码,就珍藏起来吧. 二 实例分析: 1 #include <stdio.h> 2 3 int ...

  7. 多线程系列(十九) -Future使用详解

    一.摘要 在前几篇线程系列文章中,我们介绍了线程池的相关技术,任务执行类只需要实现Runnable接口,然后交给线程池,就可以轻松的实现异步执行多个任务的目标,提升程序的执行效率,比如如下异步执行任务 ...

  8. 关于使用Kotlin开发SpringBoot项目使用@Transactional和@Autowired的报错问题

    原文地址: 关于使用Kotlin开发SpringBoot项目使用@Transactional和@Autowired的报错问题 - Stars-One的杂货小窝 问题描述 最近在开发一个订单模块,需要出 ...

  9. 投屏Sink端音频底层解码并用OpenSLES进行播放

    一.代码分析 在公司项目中,音频解码及播放是把数据传到Java层进行解码播放的,其实这个步骤没有必要,完全可以在底层进行处理. 通过代码发现其实也做了在底层进行解码,那么为啥不直接使用底层解码播放呢, ...

  10. 实时3D渲染它是如何工作的?可以在哪些行业应用?

    随着新兴技术--3D渲染的发展,交互应用的质量有了极大的提高.用实时三维渲染软件创建的沉浸式数字体验,几乎与现实没有区别了.随着技术的逐步改进,在价格较低的个人工作站上渲染3D图像变得更加容易,设计师 ...