【玩转SpringBoot】异步任务执行与其线程池配置

springboot通过AsyncConfigurer接口实现异步线程池自动化配置组件 springboot提供了org.springframework.scheduling.annotation.AsyncConfigurer接口让开发人员可以自定义线程池执行器;框架默认提供了一个空的实现类AsyncConfigurerSupport,不过两个方法体内部提供的都是空实现; 1.首先看下AsyncConfigurer接口 public interface AsyncConfigurer { /** * 方法返回一个实际执行线程的线程池 */ @Nullable defaul. 阅读详情

同步代码写起来简单,但就是怕遇到耗时操作,会影响效率和吞吐量。

此时异步代码才是王者,但涉及多线程和线程池,以及异步结果的获取,写起来颇为麻烦。

不过在遇到SpringBoot异步任务时,这个问题就不存在了。 因为Spring家族是最替用户考虑的。

结果就是, 像同步一样简单,像异步一样强大 。


众所熟悉的同步代码


先准备一些代码,为了模拟耗时操作,在其中加入线程睡眠语句。

同时打印出运行这些代码的线程信息。 如下图01:


其中一个是没有返回值的,一个是有返回值的。

然后把它注入到另一个类里进行调用,在调用时也输出一下主线程信息。 如下图02:


下面是输出结果,如下图03:


可以看到这些代码运行在 主线程 中,所以这些代码的耗时操作会影响主线程。

首选的方案就是把耗时操作 放入另一个线程中 执行(通常称为工作线程),把主线程解放出来。


同步代码的异步化改造


由于SpringBoot已经帮我们做好了一切,只需按要求改造即可,只需两步,真的是非常简单。

第一步 ,引入启用异步任务的注解, @EnableAsync ,如下图04:


第二步 ,在原来的方法上标上 @Async 注解,如下图05:


这就好了,然后像普通方法一样调用,如下图06:


看下输出结果,如下图07:


可以看到主线程的id是1,而且瞬间执行完。 任务在另一个线程id为17的线程中执行,且等耗时操作执行完后才结束。

代码完全不变,只需加两个注解,同步立马变成异步啦。 简直爽歪歪了。

主要是因为这个方法没有返回值,如果有的话, 只需改下返回类型即可 。

SpringBoot一共支持三种返回类型,来逐一看下。

第一种 ,返回类型为Java的 Future<?> ,如下图08:


熟悉Java多线程的朋友对这个类都应该不陌生。 为了代码能正常编译,在方法最后需要return一个这样的类型。

在同步代码中,我们原来return的是一个Object类型,显然不满足需求,所以SpringBoot就想了一个办法。

新增了一个类, AsyncResult ,使用它进行类型适配,这也是此类的主要作用,保证编译通过。

这个类就像一个“类型”占位符一样,如果你真正了解Java多线程的话就会明白,否则绝对不明白。

然后就像普通方法调用一样调用它,接着通过while循环等待异步任务完成后,输出返回结果。

注意,我特意输出了一下方法调用返回的future变量,如下图09:


输出结果如下图10:


可以看到任务是在线程id为17的线程中执行,主线程不断睡眠等待,直到任务完成后才获取到任务的返回结果。

重要时刻来临,可以看到我们输出的future变量类型是Java的FutureTask类,而我们实际在代码中return的是Spring的AsyncResult类。

是不是很奇怪呢? 其实一点都不怪,这和Java多线程有关,如果还不明白的话,后面有说明。

第二种 ,返回类型为Spring的 ListenableFuture<?> ,如下图11:

SpringBoot异步执行:@Async注解与线程池配置 SpringBoot的异步执行机制基于Spring Framework的@Async注解,它允许方法在调用者线程之外的独立线程中执行。这种机制特别适用于处理耗时操作,如发送电子邮件、文件处理、第三方API调用等,可以有效避免阻塞主线程,提高应用响应性。SpringBoot继承了Spring的异步特性,并通过自动配置简化了异步支持的启用过程。/*** 启用SpringBoot异步支持的示例应用*/@EnableAsync // 启用异步执行支持/*** 记录异步方法执行情况的切面*/ 阅读详情

相关推荐

Springboot 配置线程池创建线程和配置 @Async 异步操作线程池

众所周知,创建显示线程和直接使用未配置的线程池创建线程,都会被阿里的大佬给diss,所以我们要规范的创建线程。至于 @Async 异步任务的用处是不想等待方法执行完就返回结果,提高软件前台响应速度,一个程序中会用到很多异步方法,所以需要使用线程池管理,防止影响性能。

泡泡的博客 5326

SpringBoot异步及线程池配置

SpringBoot异步及线程池配置 - 乐之者v - 博客园 参考资料:springboot线程池的使用和扩展_程序员欣宸的博客-CSDN博客_springboot线程池 乐之者 一生编程。快乐编程。 SpringBoot异步及线程池配置 异步方法注解@Async 在SpringBoot中进行异步处理,可以使用异步注解@Async和@EnableAsync。 @Async注解表示异步,如:@Async("asyncServiceExecutor"), 后面的参数asyncServiceEx

zhf_123666的博客 1245

Springboot配置Schedule定时任务线程池和Async异步线程池

Springboot配置Schedule定时任务线程池 Springboot默认的定时任务是单线程的,当我们的定时任务较多并且耗时较长时,为了提升效率我们可以给定时任务配置一个线程池,以多线程的方式执行定时任务。 代码清单: ScheduleConfig.java //启用自动化配置 @Configuration //启用定时任务 @EnableScheduling public class ScheduleConfig implements SchedulingConfigurer { @V

qinming的博客 2771

springBoot 用异步线程池实现异步事件

前言: 在软件开发过程中,经常会遇到需要预警,或者做埋点等和业务无关但又需要做的事,像钉钉预警,需要在特定场景执行,又不能影响业务。如果采用同步http处理,如果预警接口响应慢超时,将直接影响业务,使用异步线程池就可以很好地解决。 例子: 钉钉预警,用异步线程池处理。 一、代码层次 这是异步线程池的搭建处理 ...

YYXyeyue的博客 1141

[springboot]为异步任务规划自定义线程池

有的时候,我们希望将系统内的一类任务放到一个线程池,另一类任务放到另外一个线程池,所以使用Spring Boot自带的任务线程池就捉襟见肘了。

字母哥博客 1182

具身智能的建模和方法(具身智能入门一)

本文以机械臂将小红方块移动到目标位置为例对具身智能的建模和方法进行介绍,如下图所示,该例子来自https://ai-workshops.github.io/building-and-working-in-environments-for-embodied-ai-cvpr-2022/。

weixin_39699362的博客 1471

利用VS2019编写安卓APP的步骤和所遇问题的解决办法

遇到了代码错误,这个可以将鼠标箭头置于错误代码处,这样VS2019给你解决办法,给的方法不能解决,并且读了程序都没有问题,那么你应该重启软件,这样还是不能解决,你尝试重新生成解决方案,还是不能解决有可能是运用的代码与当前版本不相符和、过时了,这个时候应当运用相应版本的代码。注:VS2019编写APP的空间不是很稳定,当你写的代码没有问题,但是出现了报错,可能是空间崩溃了,这个时候可以重启软件。点击“+”号,创建密钥存储,输入“别名”、“密码”、以及下面中的任意一项,直至红色框消失后。

youbestcando的博客 7825

实现AI Agent的多Agent协作能力

在当今复杂的计算环境和应用场景中,单个AI Agent的能力往往受到限制。实现AI Agent的多Agent协作能力的目的在于通过多个Agent之间的协同工作,充分发挥各自的优势,提高整体系统的性能和效率,以解决更为复杂的问题。本文章的范围涵盖了多Agent协作的核心概念、算法原理、数学模型、项目实战以及实际应用场景等方面,旨在为读者提供全面且深入的技术指导。本文将按照以下结构进行阐述:首先介绍多Agent协作的背景知识,包括目的范围、预期读者和文档结构等;

AI Python 编程之道的博客 1487

月薪30k+的工业视觉,必备Java+YOLO技能(工业级落地全拆解)

30k+工业视觉岗的核心不是算法调参,而是用Java把YOLO落地到工业场景的能力——稳运行、能对接、可管理是高薪的核心壁垒;必备技能分五层:模型工业级适配、Java推理核心、SpringBoot后端、工业部署运维、场景适配,每层都要练到“能落地、能讲清、能避坑”;学习路径的核心是“实战驱动”:不要只学理论,从一个完整的工业项目(如锂电缺陷检测)入手,练完就能对标高薪岗。

2601_94871597的博客 529

Python 爬虫实战:全球渔业船舶捕捞记录数据采集与分析全攻略

通过本项目,我们实现了对全球渔业船舶捕捞记录数据的采集、处理和可视化,为渔业资源管理和海洋生态保护提供了数据支持。未来,可以进一步结合机器学习和深度学习技术,对捕捞行为进行预测和分类,提高对非法捕捞活动的识别能力。

2201_76125261的博客 576

64.企业级案例(上)-金融行业DDD落地全流程支付系统-附架构演进图

本文以金融支付系统为例,完整展示了DDD在企业级项目中的落地流程。首先通过事件风暴识别核心业务领域,包括交易、渠道、账务等限界上下文。在战略设计中划分上下文边界,确定交易上下文为核心域。战术设计聚焦交易上下文,详细设计了支付单聚合、值对象和支付路由服务。架构实现采用CQRS+EDA模式,通过命令端处理交易,查询端异步更新读模型,并利用防腐层隔离外部渠道。案例展示了DDD从业务探索到架构实现的全过程,体现了其在复杂业务系统中的价值。

yonggeit的博客 3046

实战 | OpenCV实现扫描文本矫正应用与实现详解(附源码)

导读 本文主要介绍使用OpenCV对扫描文本矫正的应用实例及详细实现步骤。 背景介绍 在使用打印机或扫描仪扫描文档时,由于摆放位置差异难免造成扫描文档的倾斜。本文将使用OpenCV将倾斜的文档矫正水平并去除黑边。 实现步骤 本文只针对包含大部分文字的文档做倾斜矫正,思路来源是大部分文字倾斜后同一行的也在同一条直线,通过拟合直线计算文本倾斜角度,然后旋转来实现文本倾斜矫正。 详细步骤: ①加载倾斜图像 ②灰度转换+腐蚀+膨胀 ③Canny边缘检测 + 霍夫线变换检测直线 ...

Color Space的博客 3407

(LDA新闻文本主题分析)基于 gensim训练LDA模型,进行新闻文本主题分析 完整代码+数据 可直接运行

(LDA新闻文本主题分析)基于 gensim训练LDA模型,进行新闻文本主题分析 完整代码+数据 可直接运行

机器学习深度学习业余选手 1505

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 【玩转SpringBoot】通过事件机制参与SpringBoot应用的启动过程
下一篇: 线程池开门营业招聘开发人员的一天
编程新说
博客等级 码龄19年 17粉丝 42原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值