Spring @Async的异常处理
楼主在前面的2篇文章中,分别介绍了Java子线程中通用的异常处理,以及Spring web应用中的异常处理。链接如下:
今天,要写的是被Spring @Async注解的方法中的异常处理方法。
通常,如果我们要在程序中做一个耗时的操作(例如调用其他外部模块),一般会通过异步的方式执行。
有这2种方法:
- 自行生成线程池ThreadPoolExecutor,提交任务执行
- 更方便地,使用Spring @Async注解,修饰在需要异步执行的方法上
对于第一种方法的异常处理,楼主已经在“Java子线程中的异常处理(通用)”这篇文章中介绍了,也就是提交任务后获取到Future对象,通过future.get()获取返回值的时候能够捕获到ExcecutionException。
对于Spring @Async注解的方法,如何进行异常处理呢?楼主想到了2种方法。
解决办法
方法一:配置AsyncUncaughtExceptionHandler(对于无返回值的方法)
通过AsyncConfigurer自定义线程池,以及异常处理。

@Configuration
@EnableAsync
public class SpringAsyncConfiguration implements AsyncConfigurer {
private static final Logger logger = LoggerFactory.getLogger(getClass());
@Bean
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(8);
executor.setMaxPoolSize(16);
executor.setQueueCapacity(64);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setThreadNamePrefix("SpringAsyncThread-"); return executor;
} @Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SpringAsyncExceptionHandler();
} class SpringAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
@Override
public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
logger.error("Exception occurs in async method", throwable.getMessage());
}
} }

方法二:通过AsyncResult捕获异常(对于有返回值的方法)
如果异步方法有返回值,那就应当返回AsyncResult类的对象,以便在调用处捕获异常。
因为AsyncResult是Future接口的子类,所以也可以通过future.get()获取返回值的时候捕获ExcecutionException。
异步方法:

@Service
public class AsyncService {@Async
</span><span style="color: #0000ff;">public</span> AsyncResult<String><span style="color: #000000;"> asyncMethodWithResult() {
</span><span style="color: #008000;">//</span><span style="color: #008000;"> do something(可能发生异常)</span> <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">new</span> AsyncResult("hello"<span style="color: #000000;">);
}
}

调用处捕获异常:

public class Test {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
AsyncService asyncService;
public void test() {
try {
Future future = asyncService.asyncMethodWithResult();
future.get();
} catch (ExecutionException e) {
logger.error("exception occurs", e);
} catch (InterruptedException e) {
logger.error("exception occurs", e);
}
}
}

Spring @Async的异常处理的更多相关文章
- Spring @Async开启异步任务
1. 开启异步 @SpringBootApplication @EnableAsync //开启异步任务 public class Application { @Bean(name="pro ...
- Spring Boot系列二 Spring @Async异步线程池用法总结
1. TaskExecutor Spring异步线程池的接口类,其实质是java.util.concurrent.Executor Spring 已经实现的异常线程池: 1. SimpleAsyncT ...
- spring mvc4:异常处理
前面学习过struts2的异常处理,今天来看下spring mvc4的异常处理: 一.Servlet配置文件修改 <bean id="exceptionResolver" c ...
- 使用Spring MVC统一异常处理实战
1 描述 在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的.不可预知的异常需要处理.每个过程都单独处理异常,系统的代码耦合 ...
- Spring MVC 统一异常处理
Spring MVC 统一异常处理 看到 Exception 这个单词都心慌 如果有一天你发现好久没有看到Exception这个单词了,那你会不会想念她?我是不会的.她如女孩一样的令人心动又心慌,又或 ...
- 【Spring学习笔记-MVC-15.1】Spring MVC之异常处理=404界面
作者:ssslinppp 异常处理请参考前篇博客:<[Spring学习笔记-MVC-15]Spring MVC之异常处理>http://www.cnblogs.com/sssl ...
- 使用Spring MVC统一异常处理实战<转>
1 描述 在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的.不可预知的异常需要处理.每个过程都单独处理异常,系统的代码耦合 ...
- Spring @async 方法上添加该注解实现异步调用的原理
Spring @async 方法上添加该注解实现异步调用的原理 学习了:https://www.cnblogs.com/shangxiaofei/p/6211367.html 使用异步方法进行方法调用 ...
- Spring 中的异常处理
工作中遇到这样的同事,问他活干完吗,他说开发好了,结果测试时发现各种异常情况未处理,联调测试时各种未知错误,最后联调完成比他预期的两倍工作量还多.这样的开发如果是新人还可以原谅,如果有工作经验且出现多 ...
随机推荐
- Thunder团队第五周 - Scrum会议7
Scrum会议7 小组名称:Thunder 项目名称:i阅app Scrum Master:苗威 工作照片: 参会成员: 王航:http://www.cnblogs.com/wangh013/ 李传康 ...
- 【IdentityServer4文档】- 打包和构建
打包和构建 IdentityServer 由多个 nuget 软件包组成的. IdentityServer4 nuget | github 包含 IdentityServer 核心对象模型,服务和中间 ...
- iOS-明杰解决字段冲突,及数组映射
/** 替换关键字的属性名 */ + (NSDictionary *)mj_replacedKeyFromPropertyName{ return @{@"UUID":@" ...
- Linux 路由 学习笔记 之一 相关的数据结构
http://blog.csdn.net/lickylin/article/details/38326719 从现在开始学习路由相关的代码,在分析代码之前, 我们还是先分析数据结构,把数据结构之间的关 ...
- <Effective C++>读书摘要--Templates and Generic Programming<一>
1.The initial motivation for C++ templates was straightforward: to make it possible to create type-s ...
- 在 Range 对象中,Min (14)必须小于或等于 max (-1)。
DataTable dt = ds.Tables[]; DataRow[] drs = dt.Select("Id=" + categoryID ); 解决方法:将参数用单引号阔起 ...
- lol人物模型提取(一)
前段时间去青岛搞团建去了,闲来无事逛了会儿淘宝,无想买个lol手办,意之间发现了这张店铺宣传图: 哎呀我去,这模型做得挺逼真啊,然而这家店铺是卖zoe的cosplay道具的,不是手办-_-|| ...
- tomcat执行shutdown.sh进程残留的解决办法
我们执行shutdown.sh指令的时候有时会发现进程并没有被关掉而是越来越多,这种情况一般是项目造成的,具体原因未去调查.由于tomcat自己有相应的保护机制,所以我们只需要强制结束其进程即可,下面 ...
- 第17天:CSS引入、选择器优先级(中级)
一.CSS 位置 1.行内式 css <div class="fr" style="color:red;">aa</div> 2. 内 ...
- jCanvaScript canvas的操作库
在jcscript.com上下载最新的jCanvaScript.1.5.18.min.js文件 里面有很多关于canvas的方法都已经是封装好了的,只需直接调用,但是要注意调用之前和调用之后都要写: ...