search
HomeJavajavaTutorialHow Springboot integrates RabbitMQ message queue

    Producer project

    POM dependency

    You can choose to add dependencies directly when creating the project.

    How Springboot integrates RabbitMQ message queue

    How Springboot integrates RabbitMQ message queue

    ##application file
    Because rabbitmq has a default address and user information, there is no need to proceed if it is local rabbitmq configuration.

    How Springboot integrates RabbitMQ message queue

    How Springboot integrates RabbitMQ message queue

    RabbitMQ configuration file:

    When using related switches and queues, we need The implementation declares switches and queues. If there is no corresponding information, the startup project will fail. Therefore, when using springboot to integrate rabbitmq, we can use the configuration file to declare the switch and queue and bind the relationship between the two. Since Fanout mode is currently being demonstrated, FanoutExchange is used to declare the switch, and other modes use the corresponding TopicExchange and DirectExchange to declare.

    @Configuration
    public class RabbitMQConfiguration {
    
    //声明fanout模式的交换机
    @Bean
    public FanoutExchange fanoutExchange() {
        return new FanoutExchange("fanout_order_exchange", true, false);
    }
    
    //声明队列
    @Bean
    public Queue smsQueue() {
        return new Queue("sms.fanout.queue", true);
    }
    
    @Bean
    public Queue emailQueue() {
        return new Queue("email.fanout.queue", true);
    }
    
    @Bean
    public Queue duanxinQueue() {
        return new Queue("duanxin.fanout.queue", true);
    }
    //绑定
    
    @Bean
    public Binding smsBinding() {
        return BindingBuilder.bind(smsQueue()).to(fanoutExchange());
    }
    
    @Bean
    public Binding emailBinding() {
        return BindingBuilder.bind(emailQueue()).to(fanoutExchange());
    }
    
    @Bean
    public Binding duanxinBinding() {
        return BindingBuilder.bind(duanxinQueue()).to(fanoutExchange());
    }
    }

    Producer business code
    This part of the code simply distributes messages by calling rabbitTemplate. @Service public class OrderService {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    public void makeOrder() {
        // 保存订单
        String orderId = UUID.randomUUID().toString();
        System.out.println("下单成功:" + orderId);
        // 通过MQ完成消息的分发
        // 参数1:交换机 ;参数2:路由key/队列名;参数3:消息内容
        String exchangeName = "fanout_order_exchange";
        rabbitTemplate.convertAndSend(exchangeName, "", orderId);
    }
    }

    Consumer:

    Consumer engineering is similar to producer engineering. We first need to introduce dependencies, and then make related changes in the application file configuration to start writing code. In the consumer project, we can also write rabbitmq configuration files to declare switches and queues. It is recommended to write the configuration file on the consumer side, because the consumer side is the first project to start. If the switch and queue are not created, the project startup will fail. Message listening

    We listen to the message queue through the RabbitListener annotation. It should be noted that we need to hand over the monitoring to spring management through Component annotation, otherwise we cannot receive messages from the server normally. Only one email message monitoring is given here. The duanxin and SMS queues declared by the producer above can be created by themselves. You only need to modify the queue name. @Service public class OrderService {

    @RabbitListener(queues = {"email.fanout.queue"})
    @Component
    public class FanoutEmailService {
        @RabbitHandler
        public void receive(String message) {
            System.out.println("email fanout -----》接收到" + message);
        }
    }

    Test

    First start the consumer project, and then create a test class in the producer project to send the message.

    @SpringBootTest class SpringbootOrderRabbitmqProducerApplicationTests {
    
    @Autowired
    private OrderService orderService;
    
    @Test
    void contextLoads() {
        orderService.makeOrder();
    }
    }

    After sending the message, we can find in the console that the consumer successfully accepted the message.

    How Springboot integrates RabbitMQ message queue

    Direct mode

    Producer

    The steps to create a project are the same as above.

    Configuration file

    The configuration is basically the same as above. Since this part tests the direct mode, you need to use DirectExchange to create the switch. It should be noted that the method name in this class cannot be the same as the method name in the rabbitmq configuration file above, because we use bean annotations to hand it over to spring management. If the names are the same, the project startup will fail.

    @Configuration
    public class DirectRabbitMQConfiguration {
    
    //声明direct模式的交换机
    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange("direct_order_exchange", true, false);
    }
    
    //声明队列
    @Bean
    public Queue smsDirectQueue() {
        return new Queue("sms.direct.queue", true);
    }
    
    @Bean
    public Queue emailDirectQueue() {
        return new Queue("email.direct.queue", true);
    }
    
    @Bean
    public Queue duanxinDirectQueue() {
        return new Queue("duanxin.direct.queue", true);
    }
    //绑定
    
    @Bean
    public Binding smsDirectBinding() {
        return BindingBuilder.bind(smsDirectQueue()).to(directExchange()).with("sms");
    }
    
    @Bean
    public Binding emailDirectBinding() {
        return BindingBuilder.bind(emailDirectQueue()).to(directExchange()).with("email");
    }
    
    @Bean
    public Binding duanxinDirectBinding() {
        return BindingBuilder.bind(duanxinDirectQueue()).to(directExchange()).with("duanxin");
    }
    }

    Business code

    @Service
    public class OrderService {
    
        @Autowired
        private RabbitTemplate rabbitTemplate;
    
        public void makeOrderDirect() {
            // 保存订单
            String orderId = UUID.randomUUID().toString();
            System.out.println("下单成功:" + orderId);
            String exchangeName = "direct_order_exchange";
            rabbitTemplate.convertAndSend(exchangeName, "sms", orderId);
            rabbitTemplate.convertAndSend(exchangeName, "email", orderId);
        }
    
    }

    Consumer

    Message monitoring

    is the same as above, just pay attention to the queue name.

    @RabbitListener(queues = {"email.direct.queue"})
    @Component
    public class DirectEmailService {
        @RabbitHandler
        public void receive(String message) {
            System.out.println("email direct -----》接收到" + message);
        }
    }

    Topic mode

    All of the above modes declare the relationship between switches, queues and bindings through configuration files; in fact, we can also declare them through annotations Switches and annotations.

    Producer

    Since it is declared using annotations, we do not need to create a configuration file and can directly write business code. When testing, we only need to modify the route name. For details on how to modify it, please go to the link at the beginning of the article to see how each mode is used.

    @Service
    public class OrderService {
    
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    public void makeOrderTopic() {
        // 保存订单
        String orderId = UUID.randomUUID().toString();
        System.out.println("下单成功:" + orderId);
        String exchangeName = "topic_order_exchange";
        String routingKey = "com.email";
        rabbitTemplate.convertAndSend(exchangeName, routingKey, orderId);
    }
    }

    Consumer

    The code is basically the same as above, the difference is that we bind the queue and the switch directly in the RabbitListener annotation. It should be noted that strings are used in each parameter. value corresponds to the queue, and the corresponding parameters are queue name, persistence, and automatic deletion. For the switch corresponding to exchange, the corresponding parameters are the switch name and switch type. The key corresponds to the route name.

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "email.topic.queue",durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = "topic_order_exchange",type = ExchangeTypes.TOPIC),
            key = "*.email.#"
    ))
    @Component
    public class TopicEmailService {
        @RabbitHandler
        public void receive(String message) {
            System.out.println("email topic -----》接收到" + message);
        }
    }

    The above is the detailed content of How Springboot integrates RabbitMQ message queue. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    怎么使用SpringBoot+Canal实现数据库实时监控怎么使用SpringBoot+Canal实现数据库实时监控May 10, 2023 pm 06:25 PM

    Canal工作原理Canal模拟MySQLslave的交互协议,伪装自己为MySQLslave,向MySQLmaster发送dump协议MySQLmaster收到dump请求,开始推送binarylog给slave(也就是Canal)Canal解析binarylog对象(原始为byte流)MySQL打开binlog模式在MySQL配置文件my.cnf设置如下信息:[mysqld]#打开binloglog-bin=mysql-bin#选择ROW(行)模式binlog-format=ROW#配置My

    Spring Boot怎么使用SSE方式向前端推送数据Spring Boot怎么使用SSE方式向前端推送数据May 10, 2023 pm 05:31 PM

    前言SSE简单的来说就是服务器主动向前端推送数据的一种技术,它是单向的,也就是说前端是不能向服务器发送数据的。SSE适用于消息推送,监控等只需要服务器推送数据的场景中,下面是使用SpringBoot来实现一个简单的模拟向前端推动进度数据,前端页面接受后展示进度条。服务端在SpringBoot中使用时需要注意,最好使用SpringWeb提供的SseEmitter这个类来进行操作,我在刚开始时使用网上说的将Content-Type设置为text-stream这种方式发现每次前端每次都会重新创建接。最

    SpringBoot怎么实现二维码扫码登录SpringBoot怎么实现二维码扫码登录May 10, 2023 pm 08:25 PM

    一、手机扫二维码登录的原理二维码扫码登录是一种基于OAuth3.0协议的授权登录方式。在这种方式下,应用程序不需要获取用户的用户名和密码,只需要获取用户的授权即可。二维码扫码登录主要有以下几个步骤:应用程序生成一个二维码,并将该二维码展示给用户。用户使用扫码工具扫描该二维码,并在授权页面中授权。用户授权后,应用程序会获取一个授权码。应用程序使用该授权码向授权服务器请求访问令牌。授权服务器返回一个访问令牌给应用程序。应用程序使用该访问令牌访问资源服务器。通过以上步骤,二维码扫码登录可以实现用户的快

    SpringBoot/Spring AOP默认动态代理方式是什么SpringBoot/Spring AOP默认动态代理方式是什么May 10, 2023 pm 03:52 PM

    1.springboot2.x及以上版本在SpringBoot2.xAOP中会默认使用Cglib来实现,但是Spring5中默认还是使用jdk动态代理。SpringAOP默认使用JDK动态代理,如果对象没有实现接口,则使用CGLIB代理。当然,也可以强制使用CGLIB代理。在SpringBoot中,通过AopAutoConfiguration来自动装配AOP.2.Springboot1.xSpringboot1.xAOP默认还是使用JDK动态代理的3.SpringBoot2.x为何默认使用Cgl

    spring boot怎么对敏感信息进行加解密spring boot怎么对敏感信息进行加解密May 10, 2023 pm 02:46 PM

    我们使用jasypt最新版本对敏感信息进行加解密。1.在项目pom文件中加入如下依赖:com.github.ulisesbocchiojasypt-spring-boot-starter3.0.32.创建加解密公用类:packagecom.myproject.common.utils;importorg.jasypt.encryption.pbe.PooledPBEStringEncryptor;importorg.jasypt.encryption.pbe.config.SimpleStrin

    使用Java SpringBoot集成POI实现Word文档导出使用Java SpringBoot集成POI实现Word文档导出Apr 21, 2023 pm 12:19 PM

    知识准备需要理解ApachePOI遵循的标准(OfficeOpenXML(OOXML)标准和微软的OLE2复合文档格式(OLE2)),这将对应着API的依赖包。什么是POIApachePOI是用Java编写的免费开源的跨平台的JavaAPI,ApachePOI提供API给Java程序对MicrosoftOffice格式档案读和写的功能。POI为“PoorObfuscationImplementation”的首字母缩写,意为“简洁版的模糊实现”。ApachePOI是创建和维护操作各种符合Offic

    springboot怎么整合shiro实现多验证登录功能springboot怎么整合shiro实现多验证登录功能May 10, 2023 pm 04:19 PM

    1.首先新建一个shiroConfigshiro的配置类,代码如下:@ConfigurationpublicclassSpringShiroConfig{/***@paramrealms这儿使用接口集合是为了实现多验证登录时使用的*@return*/@BeanpublicSecurityManagersecurityManager(Collectionrealms){DefaultWebSecurityManagersManager=newDefaultWebSecurityManager();

    springboot怎么配置mybatis和事务管理springboot怎么配置mybatis和事务管理May 10, 2023 pm 07:13 PM

    一、springboot与mybatis的配置1.首先,springboot配置mybatis需要的全部依赖如下:org.springframework.bootspring-boot-starter-parent1.5.1.RELEASEorg.springframework.bootspring-boot-starter-web1.5.1.RELEASEorg.mybatis.spring.bootmybatis-spring-boot-starter1.2.0com.oracleojdbc

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),