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

手把手github多模态大模型项目复现流程(小白可用)

写在前面:大家复现项目时可以把readme 丢给GPT 先了解整体需要做的流程框架,在复现项目之前先仔细阅读readme、分析项目框架,以下是我复现项目的相关流程以及遇到的问题 1. autodl租用 这里建议直接在autodl上租一个GPU进行环境配置  进行学生认证 刚开始使用无卡启动 先搭好环境后再直接开机 Autodl使用教程:AutoDL使用教程:1)创建实例 2)配置环境+上传数据 3)PyCharm2021.3专业版下载安装与远程连接完整步骤 4)实时查看tensorboard曲线情况 这里,我选择基础镜像--miniconda 3.10版本 pycharm镜像是官方已经把 PyTorch、CUDA、cuDNN 等常用深度学习工具都安装并配置好了,版本也是互相匹配的;复现论文代码时候我们一般选择miniconda,里面只有一个最小化的 Conda 环境管理器,其他所有东西都需要自己从头安装。 配置好之后和pycharm/vscode进行远程连接,教程见PyCharm专业版连接AutoDl详细教程(手把手教程!!) 以及一些操作小知识(重点),和再开机连接教程!

By Ne0inhk

STM32CubeMX、MDK(Keil MDK)、git、vscode等工具中统一编码设置(UTF-8),确保中文支持,避免乱码问题

STM32CubeMX、MDK(Keil MDK)、git、vscode等工具中统一编码设置(UTF-8),确保中文支持,避免乱码问题 * STM32CubeMX、MDK(Keil MDK)、git、vscode等工具中统一编码设置(UTF-8),确保中文支持,避免乱码问题 * 一、STM32CubeMX 编码设置 * 二、Keil MDK 编码设置 * 三、Git 编码设置 * 四、VS Code设置UTF-8编码 * 五、统一工作流建议 * MDK编码格式为UTF-8,stm32的printf中文输出到串口调试软件,中文显示乱码 * SecureCRT: * Xshell: * Putty: * MobaXterm: * 串口调试助手(如SSCOM、AccessPort等): * 如果串口调试软件不支持UTF-8编码: STM32CubeMX、MDK(Keil MDK)、git、vscode等工具中统一编码设置(

By Ne0inhk

仅限今日开源!基于Python的高性能JSON结构化编辑器架构详解

第一章:Python高性能JSON编辑器概述 在现代软件开发中,JSON(JavaScript Object Notation)作为轻量级的数据交换格式被广泛使用。随着数据规模的不断增长,对JSON文件的高效读取、编辑和写入操作提出了更高要求。传统的文本编辑方式已难以满足大型JSON文件的处理需求,因此构建一个基于Python的高性能JSON编辑器成为提升开发效率的关键工具。 核心特性 * 支持大文件流式解析,避免内存溢出 * 提供语法高亮与结构化视图,增强可读性 * 实现快速搜索与路径定位功能 * 集成校验机制,确保JSON格式合法性 技术选型对比 库名称解析速度内存占用适用场景json (标准库)中等高小到中型文件ujson高低高性能需求ijson低极低超大文件流式处理 基础解析示例 # 使用ijson进行流式解析,适用于大文件 import ijson def stream_parse_json(file_path): with open(file_path, 'rb') as f: # 逐个解析JSON对象中的事件流 parser = ijson.

By Ne0inhk
Git从零到远程协作:手把手实战指南

Git从零到远程协作:手把手实战指南

目录 序言:认识Git 1. 启程 - 安装与初体验    1.1 踏上Git之旅 - 下载与安装    1.2 第一次亲密接触 - 基础配置与仓库创建 2. 核心引擎 - 提交、历史与工作流    2.1 理解Git的“魔法” - 工作区、暂存区与仓库    2.2 记录你的足迹 - 添加(git add)与提交(git commit)    2.3 时光回溯 - 查看历史与差异(git diff) 3. 协作基石 - 分支与合并

By Ne0inhk