Spring Boot 消息队列与异步处理

Spring Boot 消息队列与异步处理

Spring Boot 消息队列与异步处理

在这里插入图片描述
28.1 学习目标与重点提示

学习目标:掌握Spring Boot消息队列与异步处理的核心概念与使用方法,包括消息队列的定义与特点、异步处理的定义与特点、Spring Boot与消息队列的集成、Spring Boot的实际应用场景,学会在实际开发中处理消息队列与异步处理问题。
重点:消息队列的定义与特点异步处理的定义与特点Spring Boot与消息队列的集成Spring Boot的实际应用场景

28.2 消息队列与异步处理概述

消息队列与异步处理是Java开发中的重要组件。

28.2.1 消息队列的定义

定义:消息队列是一种用于在不同应用程序之间传递消息的中间件,允许应用程序异步处理消息。
作用

  • 提高应用程序的性能。
  • 提高应用程序的可靠性。
  • 实现应用程序之间的解耦。

常见的消息队列

  • RabbitMQ:RabbitMQ是一种开源的消息队列。
  • ActiveMQ:ActiveMQ是一种开源的消息队列。
  • Kafka:Kafka是一种开源的消息队列。
  • Redis:Redis是一种开源的内存数据库,支持消息队列。

✅ 结论:消息队列是一种用于在不同应用程序之间传递消息的中间件,作用是提高应用程序的性能、可靠性、实现应用程序之间的解耦。

28.2.2 异步处理的定义

定义:异步处理是指应用程序在处理请求时,不阻塞主线程,而是将请求发送到消息队列,由其他线程或进程处理。
作用

  • 提高应用程序的响应速度。
  • 提高应用程序的吞吐量。
  • 提高应用程序的可扩展性。

✅ 结论:异步处理是指应用程序在处理请求时,不阻塞主线程,作用是提高应用程序的响应速度、吞吐量、可扩展性。

28.3 Spring Boot与消息队列的集成

Spring Boot与消息队列的集成是Java开发中的重要内容。

28.3.1 集成RabbitMQ的步骤

定义:集成RabbitMQ的步骤是指使用Spring Boot与RabbitMQ集成的方法。
步骤

  1. 创建Spring Boot项目。
  2. 添加所需的依赖。
  3. 配置RabbitMQ。
  4. 创建消息生产者。
  5. 创建消息消费者。
  6. 测试应用。

示例
pom.xml文件中的依赖:

<dependencies><!-- Web依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- RabbitMQ依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency><!-- 测试依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>

application.properties文件中的配置:

# 服务器端口 server.port=8080 # RabbitMQ连接信息 spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest 

消息生产者类:

importorg.springframework.amqp.rabbit.core.RabbitTemplate;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Component;@ComponentpublicclassProductMessageProducer{@AutowiredprivateRabbitTemplate rabbitTemplate;privatestaticfinalStringEXCHANGE_NAME="product-exchange";privatestaticfinalStringROUTING_KEY="product-routing-key";publicvoidsendProductMessage(String message){ rabbitTemplate.convertAndSend(EXCHANGE_NAME,ROUTING_KEY, message);System.out.println("消息已发送:"+ message);}}

消息消费者类:

importorg.springframework.amqp.rabbit.annotation.RabbitListener;importorg.springframework.stereotype.Component;@ComponentpublicclassProductMessageConsumer{@RabbitListener(queues ="product-queue")publicvoidreceiveProductMessage(String message){System.out.println("消息已接收:"+ message);// 处理消息的业务逻辑processProductMessage(message);}privatevoidprocessProductMessage(String message){// 模拟处理消息的业务逻辑try{Thread.sleep(2000);System.out.println("消息处理完成:"+ message);}catch(InterruptedException e){ e.printStackTrace();}}}

RabbitMQ配置类:

importorg.springframework.amqp.core.Binding;importorg.springframework.amqp.core.BindingBuilder;importorg.springframework.amqp.core.DirectExchange;importorg.springframework.amqp.core.Queue;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;@ConfigurationpublicclassRabbitMQConfig{@BeanpublicDirectExchangeproductExchange(){returnnewDirectExchange("product-exchange");}@BeanpublicQueueproductQueue(){returnnewQueue("product-queue");}@BeanpublicBindingproductBinding(Queue productQueue,DirectExchange productExchange){returnBindingBuilder.bind(productQueue).to(productExchange).with("product-routing-key");}}

控制器类:

importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.*;@RestController@RequestMapping("/api/products")publicclassProductController{@AutowiredprivateProductMessageProducer productMessageProducer;@PostMapping("/send")publicStringsendProductMessage(@RequestBodyString message){ productMessageProducer.sendProductMessage(message);return"消息已发送";}}

应用启动类:

importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublicclassRabbitMQApplication{publicstaticvoidmain(String[] args){SpringApplication.run(RabbitMQApplication.class, args);}}

测试类:

importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.boot.test.web.client.TestRestTemplate;importorg.springframework.boot.web.server.LocalServerPort;importstaticorg.assertj.core.api.Assertions.assertThat;@SpringBootTest(webEnvironment =SpringBootTest.WebEnvironment.RANDOM_PORT)classRabbitMQApplicationTests{@LocalServerPortprivateint port;@AutowiredprivateTestRestTemplate restTemplate;@TestvoidcontextLoads(){}@TestvoidtestSendProductMessage(){String message ="Hello, RabbitMQ!";String response = restTemplate.postForObject("http://localhost:"+ port +"/api/products/send", message,String.class);assertThat(response).contains("消息已发送");}}

✅ 结论:集成RabbitMQ的步骤包括创建Spring Boot项目、添加所需的依赖、配置RabbitMQ、创建消息生产者、创建消息消费者、测试应用。

28.4 Spring Boot的实际应用场景

在实际开发中,Spring Boot消息队列与异步处理的应用场景非常广泛,如:

  • 实现产品信息的异步处理。
  • 实现用户信息的异步处理。
  • 实现订单信息的异步处理。
  • 实现支付信息的异步处理。

示例

importorg.springframework.amqp.rabbit.core.RabbitTemplate;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Component;@ComponentclassProductMessageProducer{@AutowiredprivateRabbitTemplate rabbitTemplate;privatestaticfinalStringEXCHANGE_NAME="product-exchange";privatestaticfinalStringROUTING_KEY="product-routing-key";publicvoidsendProductMessage(String message){ rabbitTemplate.convertAndSend(EXCHANGE_NAME,ROUTING_KEY, message);System.out.println("消息已发送:"+ message);}}importorg.springframework.amqp.rabbit.annotation.RabbitListener;importorg.springframework.stereotype.Component;@ComponentclassProductMessageConsumer{@RabbitListener(queues ="product-queue")publicvoidreceiveProductMessage(String message){System.out.println("消息已接收:"+ message);processProductMessage(message);}privatevoidprocessProductMessage(String message){try{Thread.sleep(2000);System.out.println("消息处理完成:"+ message);}catch(InterruptedException e){ e.printStackTrace();}}}importorg.springframework.amqp.core.Binding;importorg.springframework.amqp.core.BindingBuilder;importorg.springframework.amqp.core.DirectExchange;importorg.springframework.amqp.core.Queue;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;@ConfigurationclassRabbitMQConfig{@BeanpublicDirectExchangeproductExchange(){returnnewDirectExchange("product-exchange");}@BeanpublicQueueproductQueue(){returnnewQueue("product-queue");}@BeanpublicBindingproductBinding(Queue productQueue,DirectExchange productExchange){returnBindingBuilder.bind(productQueue).to(productExchange).with("product-routing-key");}}importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.*;@RestController@RequestMapping("/api/products")classProductController{@AutowiredprivateProductMessageProducer productMessageProducer;@PostMapping("/send")publicStringsendProductMessage(@RequestBodyString message){ productMessageProducer.sendProductMessage(message);return"消息已发送";}}@SpringBootApplicationpublicclassRabbitMQApplication{publicstaticvoidmain(String[] args){SpringApplication.run(RabbitMQApplication.class, args);}}// 测试类@SpringBootTest(webEnvironment =SpringBootTest.WebEnvironment.RANDOM_PORT)classRabbitMQApplicationTests{@LocalServerPortprivateint port;@AutowiredprivateTestRestTemplate restTemplate;@TestvoidcontextLoads(){}@TestvoidtestSendProductMessage(){String message ="Hello, RabbitMQ!";String response = restTemplate.postForObject("http://localhost:"+ port +"/api/products/send", message,String.class);assertThat(response).contains("消息已发送");}}

输出结果

  • 访问http://localhost:8080/api/products/send,发送消息“Hello, RabbitMQ!”。
  • 控制台输出:消息已发送:Hello, RabbitMQ!。
  • 消费者控制台输出:消息已接收:Hello, RabbitMQ!,2秒后输出:消息处理完成:Hello, RabbitMQ!。

✅ 结论:在实际开发中,Spring Boot消息队列与异步处理的应用场景非常广泛,需要根据实际问题选择合适的消息队列和异步处理方法。

总结

本章我们学习了Spring Boot消息队列与异步处理,包括消息队列的定义与特点、异步处理的定义与特点、Spring Boot与消息队列的集成、Spring Boot的实际应用场景,学会了在实际开发中处理消息队列与异步处理问题。其中,消息队列的定义与特点、异步处理的定义与特点、Spring Boot与消息队列的集成、Spring Boot的实际应用场景是本章的重点内容。从下一章开始,我们将学习Spring Boot的其他组件、微服务等内容。

Read more

C++学习之旅【实战全面解析C++二叉搜索树】

C++学习之旅【实战全面解析C++二叉搜索树】

🔥承渊政道:个人主页 ❄️个人专栏: 《C语言基础语法知识》《数据结构与算法》 《C++知识内容》《Linux系统知识》 ✨逆境不吐心中苦,顺境不忘来时路!🎬 博主简介: 引言:前篇文章,小编已经介绍了关于C++中多态概念指南与核心内容介绍!相信大家应该有所收获!接下来我将带领大家继续深入学习C++的相关内容!本篇文章着重介绍关于实战全面解析C++二叉搜索树,那么这里面到底有哪些知识需要我们去学习的呢?废话不多说,带着这些疑问,下面跟着小编的节奏🎵一起学习吧! 目录 * 1.⼆叉搜索树的概念 * 2.⼆叉搜索树的性能分析 * 3.⼆叉搜索树的插⼊ * 4.⼆叉搜索树的查找 * 5.⼆叉搜索树的删除 * 6.⼆叉搜索树的实现代码 * 7.⼆叉搜索树key和key/value使⽤场景 * 7.1key搜索场景 * 7.2key/value搜索场景 * 7.3key/value⼆

By Ne0inhk
第十六届蓝桥杯省赛(软件类真题)C/C++ 大学A组

第十六届蓝桥杯省赛(软件类真题)C/C++ 大学A组

大纲: A.寻找质数 B:黑白棋 题目&解析&代码 A题 题目解析 本题的目标是枚举质数并计数,直到数到第2025个。由于2025不算太大,第2025个质数大约在17000~18000之间,完全可以在合理时间内通过简单枚举得到。 解题步骤: 从2开始遍历每个整数,判断它是否是质数。 质数判断采用试除法:对于一个数n,只需检查从2到√n的所有整数是否能整除n。若存在能整除的数,则n不是质数;否则是质数。 每找到一个质数,计数器加1。 当计数器达到2025时,输出当前的质数并结束。 优化点: 除了2以外,偶数不可能是质数,因此可以跳过偶数判断(直接步进2)。 在isPrime函数中,可以先处理特殊情况(n<2返回false),然后单独判断偶数,再对奇数进行试除,步进也可以设为2。 C++ 参考代码 以下代码实现了上述算法,并输出第2025个质数。 cpp

By Ne0inhk
初学二叉搜索树踩坑多?C++ 从原理到代码,搞定增删查全流程

初学二叉搜索树踩坑多?C++ 从原理到代码,搞定增删查全流程

🎬 个人主页:Vect个人主页 🎬 GitHub:Vect的代码仓库 🔥 个人专栏: 《数据结构与算法》《C++学习之旅》《计算机基础》 ⛺️Per aspera ad astra. 文章目录 * 1. 二叉搜索树相关概念 * 2. 二叉搜索树的操作 * 2.1. 查找节点 * 2.2. 插入节点 * 2.3. 删除节点 * 3. 二叉搜索树的实现 * 4. 二叉搜索树的应用 * 4.1. K模型 * 4.2. KV模型 1. 二叉搜索树相关概念 如下图所示,二叉搜索树(binary search tree)满足下列条件: 1. 对于根节点,左子树中所有节点的值<根节点的值&

By Ne0inhk