了解
SpringBoot要使用@Async需要以下步骤:
- 启动类增加注解 @EnableAsync
- 当前类声明为服务 @Service
- 方法上面添加注解 @Async
异步类
@Component
@Slf4j
public class TestTaskAsync {
@Async
public void testAsync01(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("任务:asyncTask-01>>>>>>>>>>>>执行完毕!");
}
@Async
public Future<String> testAsync02(){
int seconds = 2;
try {
Thread.sleep(seconds*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("I love you, always!");
return new AsyncResult<>("思考了"+seconds+"秒!");
}
}
测试类
@RestController
@Slf4j
@Api(value = "AsyncTest", tags = "异步Async")
public class AsyncTestController {
@Autowired
private TestTaskAsync testTaskAsync;
@GetMapping("/testAsync1")
@ApiOperation("spring-boot异步注解测试")
public void testAsync1(){
log.info("task-01 before---------------------->>>>");
testTaskAsync.testAsync01();
log.info("task-01 after----------------------->>>>");
}
@GetMapping("/testAsync2")
@ApiOperation("spring-boot异步注解测试(有返回值)")
public void testAsync2(){
log.info("你不爱我了么?");
Future<String> future = testTaskAsync.testAsync02();
log.info("你竟无话可说, 我们分手吧... ...");
try {
Thread.sleep(3000);
log.info(future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
注意事项
-
静态方法上的@Async会失效
-
异步方法上标注的@Transactional也会失效
-
异步执行中的异常在ExceptionHandler、HandlerExceptionResolver中是无法处理的,我们可以通过下面的方式统一处理异步执行中的异常
-
可以为异步执行配置自定义的Executor
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (ex, method, params) -> {
//这个地方可以处理异步执行中的异常
};
}
}