RabbitMQ详解(四):SpringBoot整合MQ

这篇具有很好参考价值的文章主要介绍了RabbitMQ详解(四):SpringBoot整合MQ。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

SpringBoot整合MQ

需要创建两个springboot项目,一个springboot_rabbitmq_producer生产者,一个springboot_rabbitmq_consumer消费者

fanout模式(配置文件方式)

定义生产者

  • 创建生产者工程 springboot_rabbitmq_producer

    RabbitMQ详解(四):SpringBoot整合MQ

  • pom.xml文件中添加依赖

    <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-amqp</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.amqp</groupId>
                <artifactId>spring-rabbit-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
  • application.yml文件配置

    # 服务端口
    server:
      port: 8080
    # 配置rabbitmq服务
    spring:
      rabbitmq:
        username: admin
        password: admin
        virtual-host: /
        host: 请填写自己的IP地址
        port: 5672
    
  • 生产者代码

    package com.cn.service;
    
    import org.springframework.amqp.rabbit.core.RabbitTemplate;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import java.util.UUID;
    
    @Service
    public class OrderService {
    
        @Autowired	
        /**
         * RabbitTemplate
         * 提供了编辑消息、发送消息、发送消息前的监听、发送消息后的监听等消息制造和消息监听功能,
         * 可以让我们像操作原生 RabbitMQ API 那样在 Spring 中通过 RabbitTemplate 来操作消息并发送和监听消息
         */
        private RabbitTemplate rabbitTemplate;
    
          public void createOrderFanout(String userId, String productId, int num){
            //此处模拟生成订单编号
            String orderId = UUID.randomUUID().toString();
            //定义交换机名称
            String exchangeName  = "fanout-order-exchange";
            //fanout模式不需要routeKey
            String routeKey  = "";
            rabbitTemplate.convertAndSend(exchangeName, routeKey, orderId);
        }
    }
    
  • 绑定关系,基于配置文件的形式

    package com.cn.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 FanoutRabbitmqConfig {
    
        //1.声明交换机
        @Bean
        public FanoutExchange fanoutExchange(){
         return new FanoutExchange("fanout-order-exchange", true, false);
        }
    
        //2.声明队列
        @Bean
        public Queue fanoutEmailQueue(){
            return new Queue("email.fanout.queue", true);
        }
    
        @Bean
        public Queue fanoutSmsQueue(){
            return new Queue("sms.fanout.queue", true);
        }
    
        @Bean
        public Queue fanoutWeixinQueue(){
            return new Queue("weixin.fanout.queue", true);
        }
    
        //3.交换机和队列进行绑定
        @Bean
        public Binding fanoutEmailBinding(){
            return BindingBuilder.bind(fanoutEmailQueue()).to(fanoutExchange());
        }
    
        @Bean
        public Binding fanoutSmsBinding(){
            return BindingBuilder.bind(fanoutSmsQueue()).to(fanoutExchange());
        }
    
        @Bean
        public Binding fanoutWeixinBinding(){
            return BindingBuilder.bind(fanoutWeixinQueue()).to(fanoutExchange());
        }
    }
    
  • 测试代码

    package com.cn;
    
    import com.cn.service.OrderService;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    @SpringBootTest
    class SpringbootRabbitmqFanoutProducerApplicationTests {
    
        @Autowired
        private OrderService orderService;
    
        @Test
        void testOrderFanout() {
            orderService.createOrderFanout("1","1",111);
        }
    }
    
  • 启动测试,查看图形化管理界面,可以看到交换机和队列都已创建好并且各投递了一条消息

RabbitMQ详解(四):SpringBoot整合MQ

RabbitMQ详解(四):SpringBoot整合MQ

定义消费者

  • 创建消费者工程 springboot_rabbitmq_consumer

    RabbitMQ详解(四):SpringBoot整合MQ

  • pom.xml文件中添加依赖

    <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-amqp</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.amqp</groupId>
                <artifactId>spring-rabbit-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
  • application.yml文件配置

    # 服务端口
    server:
      port: 8081
    # 配置rabbitmq服务
    spring:
      rabbitmq:
        username: admin
        password: admin
        virtual-host: /
        host: 请填写自己的IP地址
        port: 5672
    
  • 消费者-邮件服务

    package com.cn.service.fanout;
    
    import org.springframework.amqp.rabbit.annotation.RabbitHandler;
    import org.springframework.amqp.rabbit.annotation.RabbitListener;
    import org.springframework.stereotype.Service;
    
    @Service
    /**
     * @RabbitListener
     * 队列已经存在时,直接指定名称即可
     */
    @RabbitListener(queues = "email.fanout.queue")
    public class EmailConsumer {
    
        @RabbitHandler
        public void reviceMessage(String message){
            System.out.println("email.fanout.queue => 接收到了订单信息:" + message);
        }
    }
    
  • 消费者-短信服务

    package com.cn.service.fanout;
    
    import org.springframework.amqp.rabbit.annotation.RabbitHandler;
    import org.springframework.amqp.rabbit.annotation.RabbitListener;
    import org.springframework.stereotype.Service;
    
    @Service
    /**
     * @RabbitListener
     * 队列已经存在时,直接指定名称即可
     */
    @RabbitListener(queues = "sms.fanout.queue")
    public class SmsConsumer {
    
        @RabbitHandler
        public void reviceMessage(String message){
            System.out.println("sms.fanout.queue => 接收到了订单信息:" + message);
        }
    }
    
  • 消费者-微信服务

    package com.cn.service.fanout;
    
    import org.springframework.amqp.rabbit.annotation.RabbitHandler;
    import org.springframework.amqp.rabbit.annotation.RabbitListener;
    import org.springframework.stereotype.Service;
    
    @Service
    /**
     * @RabbitListener
     * 队列已经存在时,直接指定名称即可
     */
    @RabbitListener(queues = "weixin.fanout.queue")
    public class WeixinConsumer {
    
        @RabbitHandler
        public void reviceMessage(String message){
            System.out.println("weixin.fanout.queue => 接收到了订单信息:" + message);
        }
    }
    
  • 启动消费者,查看日志打印

    RabbitMQ详解(四):SpringBoot整合MQ

direct模式(配置文件方式)

定义生产者

  • 在上个案例OrderService中修改

     public void createOrderDirect(String useerId, String productId, int num){
          	//此处模拟生成订单编号
            String orderId = UUID.randomUUID().toString();
            //定义交换机名称
            String exchangeName  = "direct-order-exchange";;
            //direct模式需要routeKey
            String routeKey  = "email";
            rabbitTemplate.convertAndSend(exchangeName, routeKey, orderId);
        }
    
  • 绑定关系

    package com.cn.config;
    
    import org.springframework.amqp.core.*;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class DirectRabbitmqConfig {
    
        //1.声明交换机
        @Bean
        public DirectExchange directExchange(){
         return new DirectExchange("direct-order-exchange", true, false);
        }
    
        //2.声明队列
        @Bean
        public Queue directEmailQueue(){
            return new Queue("email.direct.queue", true);
        }
    
        @Bean
        public Queue directSmsQueue(){
            return new Queue("sms.direct.queue", true);
        }
    
        @Bean
        public Queue directWeixinQueue(){
            return new Queue("weixin.direct.queue", true);
        }
    
        //3.交换机和队列进行绑定
        @Bean
        public Binding directEmailBinding(){
            return BindingBuilder.bind(directEmailQueue()).to(directExchange()).with("email");
        }
    
        @Bean
        public Binding directSmsBinding(){
            return BindingBuilder.bind(directSmsQueue()).to(directExchange()).with("sms");
        }
    
        @Bean
        public Binding directWeixinBinding(){
            return BindingBuilder.bind(directWeixinQueue()).to(directExchange()).with("weixin");
        }
    }
    
  • 测试 代码

       @Test
        void testOrderDirect() {
            orderService.createOrderDirect("1","1",222);
        }
    
  • 启动测试,查看图形化管理界面,可以看到交换机和队列都已创建好并且只有email.direct.queue投递了一条消息

    RabbitMQ详解(四):SpringBoot整合MQ

    RabbitMQ详解(四):SpringBoot整合MQ

定义消费者

  • 同理对上个案例中的代码进行修改

  • 消费者-邮件服务

    package com.cn.service.direct;
    
    import org.springframework.amqp.rabbit.annotation.RabbitHandler;
    import org.springframework.amqp.rabbit.annotation.RabbitListener;
    import org.springframework.stereotype.Service;
    
    @Service
    @RabbitListener(queues = "email.direct.queue")
    public class DirectEmailConsumer {
    
        @RabbitHandler
        public void reviceMessage(String message){
            System.out.println("email.direct.queue => 接收到了订单信息:" + message);
        }
    }
    
  • 消费者-短信服务

    package com.cn.service.direct;
    
    import org.springframework.amqp.rabbit.annotation.RabbitHandler;
    import org.springframework.amqp.rabbit.annotation.RabbitListener;
    import org.springframework.stereotype.Service;
    
    @Service
    @RabbitListener(queues = "sms.direct.queue")
    public class DirectSmsConsumer {
    
        @RabbitHandler
        public void reviceMessage(String message){
            System.out.println("sms.direct.queue => 接收到了订单信息:" + message);
        }
    }
    
  • 消费者-微信服务

    package com.cn.service.direct;
    
    import org.springframework.amqp.rabbit.annotation.RabbitHandler;
    import org.springframework.amqp.rabbit.annotation.RabbitListener;
    import org.springframework.stereotype.Service;
    
    @Service
    @RabbitListener(queues = "weixin.direct.queue")
    public class DirectWeixinConsumer {
    
        @RabbitHandler
        public void reviceMessage(String message){
            System.out.println("weixin.direct.queue => 接收到了订单信息:" + message);
        }
    }
    
  • 启动消费者,查看日志打印

    RabbitMQ详解(四):SpringBoot整合MQ

topic模式(注解方式)

定义生产者

  • 在上个案例中修改

      public void createOrderTopic(String useerId, String productId, int num){
            String orderId = UUID.randomUUID().toString();
            String exchangeName  = "topic-order-exchange";
            String routeKey  = "com.email.xxx";
            rabbitTemplate.convertAndSend(exchangeName, routeKey, orderId);
        }
    
  • 此处不进行绑定操作,后面在消费者中使用注解形式去修改

  • 测试代码

    	@Test
        void testOrderTopic() {
            orderService.createOrderTopic("1","1",14);
        }
    
  • 启动测试,查看图形化管理界面,可以看到交换机和队列都已创建好并且只有email.direct.queue和sms.direct.queue各投递了一条消息

    RabbitMQ详解(四):SpringBoot整合MQ

    RabbitMQ详解(四):SpringBoot整合MQ

定义消费者

  • 同理对上个案例中的代码进行修改

  • 消费者-邮件服务

    package com.cn.service.topic;
    
    import org.springframework.amqp.core.ExchangeTypes;
    import org.springframework.amqp.rabbit.annotation.*;
    import org.springframework.stereotype.Service;
    
    @Service
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "email.topic.queue", durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = "topic-order-exchange", type = ExchangeTypes.TOPIC),
            key = "#.email.#"
    ))
    public class TopicEmailConsumer {
    
        @RabbitHandler
        public void reviceMessage(String message){
            System.out.println("email.topic.queue => 接收到了订单信息:" + message);
        }
    }
    
  • 消费者-短信服务

    package com.cn.service.topic;
    
    import org.springframework.amqp.core.ExchangeTypes;
    import org.springframework.amqp.rabbit.annotation.*;
    import org.springframework.stereotype.Service;
    
    @Service
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "sms.topic.queue", durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = "topic-order-exchange", type = ExchangeTypes.TOPIC),
            key = "com.#"
    ))
    public class TopicSmsConsumer {
    
        @RabbitHandler
        public void reviceMessage(String message){
            System.out.println("sms.topic.queue => 接收到了订单信息:" + message);
        }
    
    }
    
    
  • 消费者-微信服务

    package com.cn.service.topic;
    
    import org.springframework.amqp.core.ExchangeTypes;
    import org.springframework.amqp.rabbit.annotation.*;
    import org.springframework.stereotype.Service;
    
    @Service
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "weixin.topic.queue", durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = "topic-order-exchange", type = ExchangeTypes.TOPIC),
            key = "*.weixin.#"
    ))
    public class TopicWeixinConsumer {
    
        @RabbitHandler
        public void reviceMessage(String message){
            System.out.println("weixin.topic.queue => 接收到了订单信息:" + message);
        }
    }
    
  • 启动消费者,查看日志打印

    RabbitMQ详解(四):SpringBoot整合MQ文章来源地址https://www.toymoban.com/news/detail-453070.html

到了这里,关于RabbitMQ详解(四):SpringBoot整合MQ的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 单个springboot整合rabbitmq

    rabbitmq是一种消息中间件,是基于erlang语言开发的AMQP(高级消息队列协议)的开源实现。 本质是个队列,FIFO先入先出。 1.1.1 rabbitmq特性: 开源,性能优秀,稳定保障 提供可靠的消息投递模式,返回模式 于Spring AMQP完美整合,API丰富 集群模式丰富 高可用 1.1.2 rabbitmq主要结构 生产

    2024年02月10日
    浏览(53)
  • SpringBoot 整合 RabbitMQ

    由于有的 Idea 不选择插线无法创建 Spring Boot 项目,这里我们先随便选一个插件,大家也可以根据需求选择~~ 把版本改为 2.7.14 引入这两个依赖: 配置 application.yml文件 Config 类 : RabbitMQConfig 测试类: RabbitMQConfigTests 结果 当我们启动 测试类 之后就可以发现我们的 rabbitmq 界面里的

    2024年02月10日
    浏览(28)
  • SpringBoot 整合RabbitMQ

    2007 年发布,是一个在 AMQP(高级消息队列协议)基础上完成的,可复用的企业消息系统,是当前最主流的消息中间件之一。 RabbitMQ是一个由erlang开发的AMQP(Advanced Message Queue 高级消息队列协议 )的开源实现,由于erlang 语言的高并发特性,性能较好,本质是个队列,FIFO 先入先出

    2024年02月15日
    浏览(41)
  • RabbitMQ整合Springboot

    目录 一、配置 二、使用 (1)创建普通交换机 (2) 创建普通队列 (3)绑定 交换机--队列 (4)创建带有死信交换机的队列 (5)生产者 (6)消费者 (7)Message对象 (8)延时队列优化(死信实现延时,有缺陷) 三、Rabbitmq插件实现延迟队列(重点) 四、发布确认 (1)确认回调

    2024年02月15日
    浏览(31)
  • SpringBoot整合实现RabbitMQ

    本文大纲 一.RabbitMQ介绍 二.RabbitMQ的工作原理 2.1 RabbitMQ的基本结构 2.2 组成部分说明 2.3 生产者发送消息流程 2.4 消费者接收消息流程 三.SpringBoot 整合实现RabbitMQ 3.1创建mq-rabbitmq-producer(生产者)发送消息 3.1.1pom.xml中添加相关的依赖 3.1.2 配置application.yml 3.1.3 配置RabbitMQ常量类

    2024年02月17日
    浏览(36)
  • SpringBoot整合RabbitMQ(基础)

    一.环境准备 1、在pom文件中引入对应的依赖: 2、在application.yml配置文件中配置RabbitMQ: 二、整合 点对点,简单模式 ①配置文件中声明队列 ②创建生产者 消息发送成功后,在web管理页面查看: 可以看到对应队列中产生了消息 ③创建消费者 启动项目,可以看到消息成功消费:

    2024年02月11日
    浏览(27)
  • SpringBoot项目整合RabbitMQ

    消息队列(Message Queue)是分布式系统中常用的组件,它允许不同的应用程序之间通过发送和接收消息进行通信。Spring Boot提供了简单且强大的方式来整合消息队列,其中包括RabbitMQ、ActiveMQ、Kafka等多种消息队列实现。 本文将以RabbitMQ为例,详细介绍如何使用Spring Boot来整合消

    2024年02月09日
    浏览(43)
  • RabbitMQ与SpringBoot整合实践

    作者:禅与计算机程序设计艺术 2020年是一个转折点,现代化的信息社会已经开启了数字化进程,越来越多的人开始接受信息技术作为工作的一部分。相较于传统的技术岗位,人工智能、大数据、云计算领域的软件工程师更加需要具备实际项目应用能力、高超的计算机和通信

    2024年02月09日
    浏览(28)
  • springboot整合rabbitmq死信队列

    什么是死信 需要测试死信队列,则需要先梳理整体的思路,如可以采取如下方式进行配置: 从上面的逻辑图中,可以发现大致的思路: .1. 消息队列分为正常交换机、正常消息队列;以及死信交换机和死信队列。 2. 正常队列针对死信信息,需要将数据 重新 发送至死信交换机

    2024年02月11日
    浏览(33)
  • 实战:SpringBoot与RabbitMQ整合

    随着微服务架构的普及,分布式系统的复杂性也逐渐增加。在这种架构中,消息队列成为了一种常见的解决方案,用于解耦服务之间的通信。RabbitMQ是一种流行的消息队列系统,它支持多种消息传输协议,如AMQP、MQTT、STOMP等。SpringBoot是一种简化Spring应用开发的框架,它提供了

    2024年02月22日
    浏览(29)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包