在SpringBoot中对RabbitMQ三种使用方式

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

基于API的方式

        1.使用AmqpAdmin定制消息发送组件

     @Autowired
    private AmqpAdmin amqpAdmin;
    @Test
    public void amqpAdmin(){
        //1.定义fanout类型的交换器
        amqpAdmin.declareExchange(new FanoutExchange("fanout_exchange"));
        //2.定义两个默认持久化队列,分别处理email和sms
        amqpAdmin.declareQueue(new Queue("fanout_queue_email"));
        amqpAdmin.declareQueue(new Queue("fanout_queue_sms"));
        //3.将队列分别与交换器进行绑定
      
                                                //               队列名             是队列                                 交换机的名称           路由         其它参数
        amqpAdmin.declareBinding(new Binding("fanout_queue_email",Binding.DestinationType.QUEUE,"fanout_exchange","",null));
        amqpAdmin.declareBinding(new Binding("fanout_queue_sms",Binding.DestinationType.QUEUE,"fanout_exchange","",null));
    }

    

   

2.消息发送者发送消息

             创建实体类

                

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer id;
    private String name;

}

                发送消息

 

    @Autowired
    private RabbitTemplate re;
    @Test//消息发送者
    public void subPublisher(){
        User user = new User(1,"小满");
        re.convertAndSend("fanout_exchange", "", user);
    }

在SpringBoot中对RabbitMQ三种使用方式,java-rabbitmq,spring boot,rabbitmq

                        如图所以,如果我们直接发送的话就会报这个错,有两种解决方法,第一种是比较常用的让实体类User实现序列化Serializable接口,这里我们不做演示,第二种是写一个配置类,只有在RabbitMQ可以使用

import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {
    //定制JSON格式的消息转化器
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

}

在SpringBoot中对RabbitMQ三种使用方式,java-rabbitmq,spring boot,rabbitmq

        加上配置类后我们发送就不会报错了,我们也可以在RabbitMQ的可视化端口看到我们发送的消息

 

在SpringBoot中对RabbitMQ三种使用方式,java-rabbitmq,spring boot,rabbitmq

在SpringBoot中对RabbitMQ三种使用方式,java-rabbitmq,spring boot,rabbitmq

 

        3.发送完消息后接下来就是消费消息了,定义接收消息的业务

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Service
public class RabbitMQService {
    //发布订阅模式: @RabbitListener可以指定当前方法监控哪一个队列
   @RabbitListener(queues = "fanout_queue_email")//消费者可以消费多个队列的消息 
    public void subConsumerEmail(Message message){
        //当队列中有内容是方法会自动执行   推荐Object来接收
        //官网推荐Message
        byte[] body = message.getBody();//Message将数据存放在body中
        String msg = new String(body);
        System.out.println("邮件业务接收到消息:"+msg);

    }

    @RabbitListener(queues = "fanout_queue_sms") 
    public void subConsumerSms(Message message){
        byte[] body = message.getBody();
        String msg = new String(body);
        System.out.println("短信业务接收到消息:"+msg);
    }
}

        4.重新运行发送端就可以接收到我们发送的数据,接收的数据可能打印在任意一个控制台中,这是idea的机制,我们不需要管 

在SpringBoot中对RabbitMQ三种使用方式,java-rabbitmq,spring boot,rabbitmq

基于配置类的方式

        1.在config配置类中定义


import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {
    //定制JSON格式的消息转化器
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

   // 1.fanout创建一个交换机
    @Bean
    public Exchange fanoutExchange(){
        return ExchangeBuilder.fanoutExchange("fanout_exchange").build();
    }

    //2.定义消息队列
    @Bean
    public Queue fanoutQueueEmail(){
        return new Queue("fanout_queue_email");
    }
    @Bean
    public Queue fanoutQueueSms(){
        return new Queue("fanout_queue_sms");
    }

    //3.将创建的队列绑定到对应的交换机上
    @Bean
    public Binding bingingEmail(){
        return BindingBuilder.bind(fanoutQueueEmail()).to(fanoutExchange()).with("").noargs();
    }
    @Bean
    public Binding bingingSms(){
        return BindingBuilder.bind(fanoutQueueSms()).to(fanoutExchange()).with("").noargs();
    }

}

        2.为了避免api的影响,我们可以在可视化端口将基于api创建的交换机和队列删除

                1)删除交换机

在SpringBoot中对RabbitMQ三种使用方式,java-rabbitmq,spring boot,rabbitmq

 在SpringBoot中对RabbitMQ三种使用方式,java-rabbitmq,spring boot,rabbitmq

 

                2)删除队列,前面也是点击队列的名字 

在SpringBoot中对RabbitMQ三种使用方式,java-rabbitmq,spring boot,rabbitmq在SpringBoot中对RabbitMQ三种使用方式,java-rabbitmq,spring boot,rabbitmq

        可以看到我已经将交换机和消息队列都已经删除,接下来我们重新启动项目 ,配置类可以在启动的时候自动创建

在SpringBoot中对RabbitMQ三种使用方式,java-rabbitmq,spring boot,rabbitmq

 在SpringBoot中对RabbitMQ三种使用方式,java-rabbitmq,spring boot,rabbitmq

         我们的订阅发布模式也是可以正常运行

        在SpringBoot中对RabbitMQ三种使用方式,java-rabbitmq,spring boot,rabbitmq

基于注解类的方式        

        1.我们要现将基于配置类的方式注释掉,避免影响我们测试

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Service
public class RabbitMQService { 
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("fanout_queue_email"),
            exchange=@Exchange(value = "fanout_exchange",type = "fanout")
    ))
    public void subConsumerEmail(Message message){
        //当队列中有内容是方法会自动执行   推荐Object来接收
        //官网推荐Message
        byte[] body = message.getBody();//Message将数据存放在body中
        String msg = new String(body);
        System.out.println("邮件业务接收到消息:"+msg);

    }

    
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("fanout_queue_sms"),
            exchange=@Exchange(value = "fanout_exchange",type = "fanout")
    ))
    public void subConsumerSms(Message message){
        byte[] body = message.getBody();
        String msg = new String(body);
        System.out.println("短信业务接收到消息:"+msg);
    }
}

        提前将交换机和队列删除,然后运行,就会发现会在启动时会自动生成交换机和队列,测试也不会有影响

 

在SpringBoot中对RabbitMQ三种使用方式,java-rabbitmq,spring boot,rabbitmq文章来源地址https://www.toymoban.com/news/detail-537233.html

到了这里,关于在SpringBoot中对RabbitMQ三种使用方式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • Java,SpringBoot中对Stream流的运用

    详细参考:java 1.8 stream 应用-22种案例_java1.8 流案例-CSDN博客 1. 遍历  2. 汇总

    2024年02月22日
    浏览(37)
  • RabbitMQ 简单实现创建队列的三种方式

    //1. 手动创建,需在RabbitMQ中手动创建myQueue1 队列,否则报错 @RabbitListener(queues = “myQueue1”) public void process1(String message){ log.info(“MqReceiver1: {}”, message); } //2. 自动创建队列 @RabbitListener(queuesToDeclare = @Queue(“myQueue2”)) public void process2(String message){ log.info(“MqReceiver2: {}”, messa

    2024年02月15日
    浏览(30)
  • SpringBoot整合RabbitMQ,三种交换机类型示例

    在application.properties或application.yml中配置RabbitMQ服务器的连接参数: 4.1、DirectExchange(直连交换机) 消费者 生产者 测试 一个交换机对多个队列的特点: 一个队列对多个消费者特点: 4.2、FanoutExchange(扇形/广播交换机) 消费者 生产者 4.3、TopicExchange(主题交换机) 消费者 生

    2024年04月12日
    浏览(21)
  • 【SpringBoot】获取HttpServletRequest的三种方式

    线程安全 缺点: 每个方法都需要写一遍 线程安全 在 Spring 中, DemoRequestController 的 scope 是 singleton (单例),也就是说在整个 web 系统中,只有一个 DemoRequestController ;但是其中注入的 request 却是线程安全的,原因在于:使用这种方式,当 Bean (本例的 DemoRequestController )初始化

    2024年02月12日
    浏览(35)
  • springboot依赖注入的三种方式

    springboot依赖注入的三种方式 在 Spring Boot 中,使用 XML 配置依赖注入(DI)时,需要使用 bean 元素来定义 bean,并使用 property 元素来为 bean 的属性注入值或依赖对象。 以下是一个简单的示例: 在 src/main/resources 目录下创建 applicationContext.xml 文件。 在该文件中定义一个 testBean

    2023年04月23日
    浏览(36)
  • 【SpringBoot18】SpringBoot 调用外部接口的三种方式

    SpringBoot不仅继承了Spring框架原有的优秀特性,而且还通过简化配置来进一步简化了Spring应用的整个搭建和开发过程。在Spring-Boot项目开发中,存在着本模块的代码需要访问外面模块接口,或外部url链接的需求, 比如在apaas开发过程中需要封装接口在接口中调用apaas提供的接口(

    2023年04月11日
    浏览(62)
  • 【RabbitMQ笔记08】消息队列RabbitMQ之防止消息丢失的三种方式(生产者消息确认、消费者消息确认、消息持久化)

    这篇文章,主要介绍消息队列RabbitMQ之防止消息丢失的三种方式(生产者消息确认、消费者消息确认、消息持久化)。 目录 一、防止消息丢失 1.1、消息确认机制(生产者) (1)生产者丢失消息 (2)生产者消息确认机制 1.2、消息确认机制(消费者) (1)消费者丢失消息

    2024年02月02日
    浏览(44)
  • SpringBoot实现分页的三种方式

    一 自己封装Page对象实现 博客链接 二 使用sql实现分页 2.1 场景分析 前段传递给给后台什么参数? 当前页码 currentPage 每页显示条数 pageSize 后台给前端返回什么数据? 当前页数据 List 总记录数 totalCount 2.2 前段代码 2.3 后端代码 PageBean mapper service impl controller 三 使用PageHelper插件

    2024年02月10日
    浏览(36)
  • SpringBoot实现固定、动态定时任务 | 三种实现方式

    阅读完本文:🐱‍👓 知晓 SpringBoot 用注解如何实现定时任务 明白 SpringBoot 如何实现一个动态定时任务 (与数据库相关联实现) 理解 SpringBoot 实现设置时间执行定时任务 (使用 ThreadPoolTaskScheduler 实现) 用注解实现是真的简单,只要会 cron 表达式就行。🧙‍♂️ 第一步 :

    2024年02月16日
    浏览(29)
  • SpringBoot导出Word文档的三种方式

    1、直接在Java代码里创建Word文档,设置格式样式等,然后导出。(略) 需要的见:https://blog.csdn.net/qq_42682745/article/details/120867432 2、富文本转换后的HTML下载为Word文档。相当于把HTML转为Word导出 3、使用模板技术导出。固定格式、可以写入不同数据 其他: springboot版本:2.7.11 导

    2024年02月02日
    浏览(41)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包