Spring Boot 之异步执行方法
前言:
最近的时候遇到一个需求,就是当服务器接到请求并不需要任务执行完成才返回结果,可以立即返回结果,让任务异步的去执行。开始考虑是直接启一个新的线程去执行任务或者把任务提交到一个线程池去执行,这两种方法都是可以的。但是Spring 这么强大,肯定有什么更简单的方法,就 google 了一下,还真有呢。就是使用 @EnableAsync 和 @Async 这两个注解就 ok 了。

给方法加上 @Async 注解
package me.deweixu.aysncdemo.service;
public interface AsyncService {
void asyncMethod(String arg);
}
package me.deweixu.aysncdemo.service.ipml;
import me.deweixu.aysncdemo.service.AsyncService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncServiceImpl implements AsyncService {
@Async
@Override
public void asyncMethod(String arg) {
System.out.println("arg:" + arg);
System.out.println("=====" + Thread.currentThread().getName() + "=========");
}
}
@EnableAsync
在启动类或者配置类加上 @EnableAsync 注解
package me.deweixu.aysncdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@EnableAsync
@SpringBootApplication
public class AysncDemoApplication {
public static void main(String[] args) {
SpringApplication.run(AysncDemoApplication.class, args);
}
}
测试
package me.deweixu.aysncdemo;
import me.deweixu.aysncdemo.service.AsyncService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AysncDemoApplicationTests {
@Autowired
AsyncService asyncService;
@Test
public void testAsync() {
System.out.println("=====" + Thread.currentThread().getName() + "=========");
asyncService.asyncMethod("Async");
}
}
=====main=========
2018-03-25 21:30:31.391 INFO 28742 --- [ main] .s.a.AnnotationAsyncExecutionInterceptor : No task executor bean found for async processing: no bean of type TaskExecutor and no bean named 'taskExecutor' either
arg:Async
=====SimpleAsyncTaskExecutor-1=========
从上面的结果看 asyncService.asyncMethod("Async") 确实异步执行了,它使用了一个新的线程。
指定 "Executor"
从上面执行的日志可以猜测到 Spring 默认使用 SimpleAsyncTaskExecutor 来异步执行任务的,可以搜索到这个类。 @Async 也可以指定自定义的 Executor。
在启动类中增加自定义的 Executor
package me.deweixu.aysncdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@EnableAsync
@SpringBootApplication
public class AysncDemoApplication {
public static void main(String[] args) {
SpringApplication.run(AysncDemoApplication.class, args);
}
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
return new ThreadPoolTaskExecutor();
}
}
指定 "Executor"
package me.deweixu.aysncdemo.service.ipml;
import me.deweixu.aysncdemo.service.AsyncService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncServiceImpl implements AsyncService {
@Async("threadPoolTaskExecutor")
@Override
public void asyncMethod(String arg) {
System.out.println("arg:" + arg);
System.out.println("=====" + Thread.currentThread().getName() + "=========");
}
}
这样在异步执行任务的时候就使用 threadPoolTaskExecutor
设置默认的
Executor
上面提到如果 @Async 不指定 Executor 就默认使用 SimpleAsyncTaskExecutor,其实默认的 Executor 是可以使用 AsyncConfigurer 接口来配置的
@Configuration
public class SpringAsyncConfig implements AsyncConfigurer { @Override
public Executor getAsyncExecutor() {
return new ThreadPoolTaskExecutor();
} }
异常捕获
在异步执行的方法中是可能出现异常的,我们可以在任务内部使用 try catch 来处理异常,当任务抛出异常时, Spring 也提供了捕获它的方法。
实现 AsyncUncaughtExceptionHandler 接口
public class CustomAsyncExceptionHandler
implements AsyncUncaughtExceptionHandler { @Override
public void handleUncaughtException(
Throwable throwable, Method method, Object... obj) { System.out.println("Exception message - " + throwable.getMessage());
System.out.println("Method name - " + method.getName());
for (Object param : obj) {
System.out.println("Parameter value - " + param);
}
} }
实现 AsyncConfigurer 接口重写 getAsyncUncaughtExceptionHandler 方法
@Configuration
public class SpringAsyncConfig implements AsyncConfigurer { @Override
public Executor getAsyncExecutor() {
return new ThreadPoolTaskExecutor();
} @Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new CustomAsyncExceptionHandler();
} }
改写 asyncMethod 方法使它抛出异常
@Async
@Override
public void asyncMethod(String arg) {
System.out.println("arg:" + arg);
System.out.println("=====" + Thread.currentThread().getName() + "=========");
throw new NullPointerException();
}
运行结果:
=====main=========
arg:Async
=====threadPoolTaskExecutor-1=========
Exception message - Async NullPointerException
Method name - asyncMethod
Parameter value - Async
正确捕获到了异常。
我是小架,我们
下篇文章见!
Spring Boot 之异步执行方法的更多相关文章
- Spring Boot Async异步执行
异步调用就是不用等待结果的返回就执行后面的逻辑,同步调用则需要等带结果再执行后面的逻辑. 通常我们使用异步操作都会去创建一个线程执行一段逻辑,然后把这个线程丢到线程池中去执行,代码如下: Execut ...
- 使用spring的@Async异步执行方法
应用场景: 1.某些耗时较长的而用户不需要等待该方法的处理结果 2.某些耗时较长的方法,后面的程序不需要用到这个方法的处理结果时 在spring的配置文件中加入对异步执行的支持 <beans x ...
- spring boot启动后执行方法
@Componentpublic class InitProject implements ApplicationRunner { private static final Logger logger ...
- Spring boot 配置异步处理执行器
示例如下: 1. 新建Maven 项目 async-executor 2.pom.xml <project xmlns="http://maven.apache.org/POM/4.0 ...
- 使用Spring Boot和AspectJ实现方法跟踪基础结构
了解如何使用Spring Boot和AspectJ实现方法跟踪基础结构!最近在优锐课学习收获颇多,记录下来大家一起进步! 在我们的应用程序中,获取方法的堆栈跟踪信息可能会节省很多时间.具有输入输出参数 ...
- Spring Boot @Async 异步任务执行
1.任务执行和调度 Spring用TaskExecutor和TaskScheduler接口提供了异步执行和调度任务的抽象. Spring的TaskExecutor和java.util.concurre ...
- Spring Boot 定时+多线程执行
Spring Boot 定时任务有多种实现方式,我在一个微型项目中通过注解方式执行定时任务. 具体执行的任务,通过多线程方式执行,单线程执行需要1小时的任务,多线程下5分钟就完成了. 执行效率提升10 ...
- Spring Boot程序的执行流程
Spring Boot的执行流程如下图所示:(图片来源于网络) 上图为SpringBoot启动结构图,我们发现启动流程主要分为三个部分,第一部分进行SpringApplication的初始化模块,配置 ...
- Spring Boot 初始化运行特定方法
Spring Boot提供了两种 “开机自启动” 的方式,ApplicationRunner和CommandLineRunner 这两种方式的目的是为了满足,在容器启动时like执行某些方法.我们可以 ...
随机推荐
- oracle将时间加一天,加小时,加分,加秒
前言 oracle 时间类型可以直接相加,但加的是天,以天为单位,我们了解了这个,加一天,一小时,一分,一秒就都简单了. 加一天 select to_date('2019-08-15 22:03:10 ...
- Grafana+Prometheus 监控 MySQL
转自:Grafana+Prometheus 监控 MySQL 架构图 环境 IP 环境 需装软件 192.168.0.237 mysql-5.7.20 node_exporter-0.15.2.lin ...
- Can not find the tag library descriptor for “http://java.sun.com/jstl/core"
此文原博文地址:https://blog.csdn.net/kolamemo/article/details/51407467 按照查到的资料,JSTL taglib需要jstl.jar来支持.在1. ...
- ubuntu上的安装.netcore2.1
.net core 在ubuntu上安装比较容易,依次执行正面语句即可 sudo apt-get install curl curl https://packages.microsoft.com/ke ...
- vue发送ajax请求
一.vue-resource 1.简介 一款vue插件,用于处理ajax请求,vue1.x时广泛应用,现不被维护. 2.使用流程 step1:安装 [命令行输入] npm install vue-re ...
- boostrap 学习笔记
bootstrap : 是全球最受欢迎的前端组件库,用于开发响应式布局.移动设备优先的 WEB 项目. 用于项目样式的快速搭建,真的是..特别快.. 随便找两个cdn引用就能使用了. https:// ...
- 【转】java的string中,关于split空串总会返回单个元素的数组
原地址:http://blog.sina.com.cn/s/blog_6f3da9650102x03c.html public class Split { public static void mai ...
- linux下安装oracle数据库--干货
1.修改系统名称,关闭防火墙,selinux.2.挂载镜像,并写入开机自动挂载.挂载点为/mnt/yummount -t iso9660 -o,loop /soft/Centos6.iso /mnt/ ...
- PyCharm如何导入python项目,并配置虚拟环境
Pycharm导入python项目 进入PyCharm后,点击File→Open,然后在弹窗中选择需要导入项目的文件夹: 打开了python项目后,需要配置该项目对应的python才可以正常运行: 配 ...
- How to Check Device UUID or File System UUID. (Doc ID 1505398.1)
How to Check Device UUID or File System UUID. (Doc ID 1505398.1) APPLIES TO: Linux OS - Version Orac ...