异步
- 开注解@EnableAsync
- 在要异步执行的方法上加@Async,必须返回void
获取结果
异步方法返回Future<>
public void testAsyncAnnotationForMethodsWithReturnType()
throws InterruptedException, ExecutionException {
Future<String> future = asyncAnnotationExample.asyncMethodWithReturnType();
while (true) {
if (future.isDone()) {
System.out.println("Result from asynchronous process - " + future.get());
break;
}
System.out.println("Continue doing something else. ");
Thread.sleep(1000);
}
}
@Service
public class AsyncServiceImpl implements AsyncService {
@Async
@Override
public Future<Boolean> generateReport(String msg) throws InterruptedException {
Thread.sleep(5000);
System.out.println("异步任务执行完成" + msg);
return new AsyncResult<>(true);
}
}
自定义Executor
设置bean
@Bean
public Executor asyncExecutor(){
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(2); //设置线程池的基本大小为2,即使线程池中的线程空闲,线程池也会保持至少有这么多的线程
threadPoolTaskExecutor.setMaxPoolSize(2); //设置线程池的最大大小为2,这表示即使排队任务的数量增加,线程池也只能增加到这个数量的线程
threadPoolTaskExecutor.setQueueCapacity(500); //设置线程池的队列容量为500。如果所有的线程都在忙,新来的任务会被放在队列里面,等待有线程空闲出来
threadPoolTaskExecutor.initialize(); //初始化线程池
return threadPoolTaskExecutor;
}
注入使用
@Async("asyncExecutor")
public void asyncMethodWithConfiguredExecutor() {
System.out.println("Execute method with configured executor - "
+ Thread.currentThread().getName());
}
全局默认Executor
@Configuration
public class AsyncConfiguration implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
//创建操作
}
}
异常处理
当方法返回类型是Future时,异常处理很容易。*Future.get()*方法将抛出异常。
但如果返回类型为void,**异常将不会传播到调用线程。**因此,我们需要添加额外的配置来处理异常。
我们将通过实现AsyncUncaughtExceptionHandler接口来创建自定义异步异常处理程序。当存在任何未捕获的异步异常时,将调用handleUncaughtException ()方法
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接口中的下一个方法
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new CustomAsyncExceptionHandler();
}