小工具知识网

当前位置: 首页 > 行业知识 > @EnableAsync的使用、进阶、源码分析

行业知识

@EnableAsync的使用、进阶、源码分析

2026-12-06 09:00:43 来源:互联网转载

@EnableAsync使用

基础使用

使用@EnableAsync开启异步切面,然后在异步调用的方法上加上@Asyc注解即可

@SpringBootApplication@EnableAsync //开启异步切面public class SpringdemoApplication {    public static void main(String[] args) {        SpringApplication.run(SpringdemoApplication.class, args);    }}
@Servicepublic class AsyncTestServiceImpl implements AsyncTestService {    @Async //异步    @Override    public void invokeAsyncTest01() {        System.out.println(Thread.currentThread() + "运行了invokeAsyncTest01方法!");    }}

自定义异步注解

@Async注解是异步切面默认的异步注解,我们可以在@EnableAsync(annotation = AsyncCustom.class)开启异步切面时指定自定义的异步注解

@Target({ElementType.TYPE, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface AsyncCustom {}
@SpringBootApplication@EnableAsync(annotation = AsyncCustom.class)public class SpringdemoApplication {    public static void main(String[] args) {        SpringApplication.run(SpringdemoApplication.class, args);    }}
@Servicepublic class AsyncTestServiceImpl implements AsyncTestService {    @AsyncCustom //异步    @Override    public void invokeAsyncTest01() {        System.out.println(Thread.currentThread() + "运行了invokeAsyncTest01方法!");    }}

@EnableAsync进阶

线程池配置

配置默认线程池

当@Async注解的value没有指定线程池名称时,将会使用此线程池,不手动设置默认线程池,系统也会给你创建一个默认线程池(详细流程请看 线程池获取优先级)。

@Slf4j@Componentpublic class AsyncConfig implements AsyncConfigurer {/*** 设置默认线程池**/    @Override    public Executor getAsyncExecutor() {//此处最好使用new ThreadPoolExecutor显示创建线程池,SimpleAsyncTaskExecutor没有复用线程        SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();        taskExecutor.setThreadNamePrefix("CustomAsync-Test-");        return taskExecutor;    }}
@Servicepublic class AsyncTestServiceImpl implements AsyncTestService {    @Async    @Override    public void invokeAsyncTest01() {        System.out.println(Thread.currentThread() + "运行了invokeAsyncTest01方法!");    }}

指定线程池 (建议,根据业务进行线程池隔离)

当@Async注解的value有指定线程池名称时,将会使用容器中beanname=此value值的Executor线程池

@Configurationpublic class TaskExecutorConfig {    @Bean    public Executor deleteFileExecutor() {//此处最好使用new ThreadPoolExecutor显示创建,SimpleAsyncTaskExecutor没有复用线程        SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();        taskExecutor.setThreadNamePrefix("delete-file-");        return taskExecutor;    }    @Bean    public Executor sendEmailExecutor() {//此处最好使用new ThreadPoolExecutor显示创建线程池,SimpleAsyncTaskExecutor没有复用线程        SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();        taskExecutor.setThreadNamePrefix("send-email-");        return taskExecutor;    }}
@Servicepublic class AsyncTestServiceImpl implements AsyncTestService {    @Async("deleteFileExecutor")    @Override    public void deleteFile() {        System.out.println(Thread.currentThread() + "运行了deleteFile方法!");    }    @Async("sendEmailExecutor")    @Override    public void sendEmail() {        System.out.println(Thread.currentThread() + "运行了sendEmail方法!");    }}

异步任务结果

只要是异步,一般都有可能用到需要返回结果的异步任务,当然@Async也支持异步结果返回,目前仅支持CompletableFuture、ListenableFuture、Future

CompletableFuture

@RestController@RequestMapping("/testasync")public class TestAsyncController {    @Autowired    private AsyncTestService asyncTestService;    @GetMapping("/test02")    public void test02() {        CompletableFuture completableFuture = asyncTestService.invokeAsyncTest02();        completableFuture.thenAccept(System.out::println);    } }
@Servicepublic class AsyncTestServiceImpl implements AsyncTestService {    @Async    @Override    public CompletableFuture invokeAsyncTest02() {        System.out.println(Thread.currentThread() + "运行了invokeAsyncTest02方法!");        return CompletableFuture.completedFuture("Hello world!");    }}

ListenableFuture

@RestController@RequestMapping("/testasync")public class TestAsyncController {    @Autowired    private AsyncTestService asyncTestService;    @GetMapping("/test03")    public void test03() {        ListenableFuture stringListenableFuture = asyncTestService.invokeAsyncTest03();        stringListenableFuture.addCallback(System.out::println, System.out::println);    }}
@Servicepublic class AsyncTestServiceImpl implements AsyncTestService {    @Async    @Override    public ListenableFuture invokeAsyncTest03() {        System.out.println(Thread.currentThread() + "运行了invokeAsyncTest03方法!");        return new AsyncResult("Hello World!");    }}

Future

@RestController@RequestMapping("/testasync")public class TestAsyncController {    @Autowired    private AsyncTestService asyncTestService;    @GetMapping("/test04")    public void test04() throws ExecutionException, InterruptedException {        Future future = asyncTestService.invokeAsyncTest04();        String str = future.get();        System.out.println(str);    }}
@Servicepublic class AsyncTestServiceImpl implements AsyncTestService {    @Async    @Override    public Future invokeAsyncTest04() {        System.out.println(Thread.currentThread() + "运行了invokeAsyncTest04方法!");        return new AsyncResult("Hello World!");    }}

Future、ListenableFuture、CompletableFuture区别

  • Future为异步任务调用的结果

  • ListenableFuture继承了Future,所以也为异步任务调用的结果,但是ListenableFuture还阔以添加两个回调函数,成功回调和异常回调

  • CompletableFuture也继承了Future,所以也为异步任务调用的结果,但是CompletableFuture阔以对异步任务进行编排

    异常处理器

    当返回值是Future及其子类

    此时,如果异步任务在执行时抛出异常时,异常先会存储在Future中并记录状态,当正真调用future.get()等获取结果函数时才会抛出异常。

    @RestController@RequestMapping("/testasync")public class TestAsyncController {    @Autowired    private AsyncTestService asyncTestService;        @GetMapping("/test04")    public void test04() throws ExecutionException, InterruptedException {        Future future = asyncTestService.invokeAsyncTest04();        //此时当当前线程获取结果时 才会抛出异常        String str = future.get();        System.out.println(str);    }}
    @Servicepublic class AsyncTestServiceImpl implements AsyncTestService {    @Async    @Override    public Future invokeAsyncTest04() {        System.out.println(Thread.currentThread() + "运行了invokeAsyncTest04方法!");        if(true){            throw new IllegalArgumentException("Hello sendEmailExecutor Exception!");        }        return new AsyncResult("Hello World!");    }}

    当返回值是非Future

    返回类型非Future时,任务发生异常将会调用异常处理器处理异常。异常处理器阔以AsyncConfigurer 实现类的getAsyncUncaughtExceptionHandler方法手动设置,如果未设置异常处理器,系统将会给你创建一个默认的SimpleAsyncUncaughtExceptionHandler异常处理器,此默认异常处理器异常处理器只对异常进行了日志输出

    @Slf4j@Componentpublic class AsyncConfig implements AsyncConfigurer {    @Override    public Executor getAsyncExecutor() {        SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();        taskExecutor.setThreadNamePrefix("CustomAsync-Test-");        return taskExecutor;    }/*** 当异步任务调用出现时将会调用此异常处理器 可在此记录日志,补偿机制等**/    @Override    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {        return (ex, method, params) -> {            System.err.println("Unexpected exception occurred invoking async method: " + method + ":" + ex.getMessage());        };    }}
    @RestController@RequestMapping("/testasync")public class TestAsyncController {    @Autowired    private AsyncTestService asyncTestService;    @GetMapping("/test06")    public void test06() {        asyncTestService.invokeAsyncTest06();    }}
    @Servicepublic class AsyncTestServiceImpl implements AsyncTestService {    @Async    @Override    public void invokeAsyncTest06() {        System.out.println(Thread.currentThread() + "运行了invokeAsyncTest06方法!");        throw new IllegalArgumentException("Hello Exception!");    }}

    扩展异常处理器

    原因

    博主通过源码发现,异常处理器只能设置一个,且后续所有@Async使用的线程池全都只有走我们设置的默认异常处理器,如果我们根据业务划分了线程池,不同线程池的异常想走不同的处理逻辑,就只有在我们手动设置的异常处理器中进行逻辑判断,非常的不优雅。

    博主的解决方案
    1. 扩展@Async注解,添加exceptionHandler属性指定异常处理器AsyncUncaughtExceptionHandler 的容器名
    2. 在设置AsyncConfigurer 实现类getAsyncUncaughtExceptionHandler方法设置一个自定义异常处理器,此处理器读取异常方法@Async的exceptionHandler属性值,然后获取到容器中名为exceptionHandler属性值的异常处理器
    3. 如果能在容器找到给定容器名称的异常处理器,就走此异常处理器
    4. 如果不能找到给定容器名称的处理器,就走默认异常处理器
    5. 如果没有设置@Async的exceptionHandler属性值,也走默认异常处理器
    方案实现

    扩展@Async注解,添加@JokerAsync继承@Async,添加exceptionHandler属性

    @Target({ElementType.TYPE, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documented@Asyncpublic @interface JokerAsync {    @AliasFor(annotation = Async.class)    String value() default "";    String exceptionHandler() default "";}

    把AsyncConfigurer 实现类getAsyncUncaughtExceptionHandler方法设置一个自定义异常处理器,此处理器读取异常方法@Async的exceptionHandler属性值,然后获取到容器中名为exceptionHandler属性值的异常处理器

    @Slf4j@Componentpublic class AsyncConfig implements AsyncConfigurer {    @Autowired(required = false)    private Map exceptionHandlerMap = new HashMap();    private final AsyncUncaughtExceptionHandler defaultExceptionHandler = new SimpleAsyncUncaughtExceptionHandler();    @Override    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {        return (ex, method, params) -> {            String qualifier = getExceptionHandlerQualifier(method);            AsyncUncaughtExceptionHandler exceptionHandler = null;            if (Objects.nonNull(qualifier) && qualifier.length() > 0) {                exceptionHandler = exceptionHandlerMap.get(qualifier);            }            if (Objects.isNull(exceptionHandler)) {                exceptionHandler = defaultExceptionHandler;            }            exceptionHandler.handleUncaughtException(ex, method, params);        };    }    protected String getExceptionHandlerQualifier(Method method) {        JokerAsync async = AnnotatedElementUtils.findMergedAnnotation(method, JokerAsync.class);        if (async == null) {            async = AnnotatedElementUtils.findMergedAnnotation(method.getDeclaringClass(), JokerAsync.class);        }        return (async != null ? async.exceptionHandler() : null);    }}

    测试示例代码

    @Slf4j@Componentpublic class DeleteFileAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {    @Override    public void handleUncaughtException(Throwable ex, Method method, Object... params) {        log.error("DeleteFileAsyncUncaughtExceptionHandler Unexpected exception occurred invoking async method: " + method, ex);    }}
    @Slf4j@Componentpublic class SendFileAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {    @Override    public void handleUncaughtException(Throwable ex, Method method, Object... params) {        log.error("SendFileAsyncUncaughtExceptionHandler Unexpected exception occurred invoking async method: " + method, ex);    }}
    @Servicepublic class AsyncTestServiceImpl implements AsyncTestService {    @JokerAsync(exceptionHandler = "deleteFileAsyncUncaughtExceptionHandler")    @Override    public void deleteFile() {        System.out.println(Thread.currentThread() + "运行了deleteFile方法!");        throw new IllegalArgumentException("Hello deleteFileExecutor Exception!");    }    @JokerAsync(exceptionHandler = "sendFileAsyncUncaughtExceptionHandler")    @Override    public void sendEmail() {        System.out.println(Thread.currentThread() + "运行了sendEmail方法!");        throw new IllegalArgumentException("Hello sendEmailExecutor Exception!");    }}
    @RestController@RequestMapping("/testasync")public class TestAsyncController {    @Autowired    private AsyncTestService asyncTestService;    @GetMapping("/sendEmail")    public void sendEmail() {        asyncTestService.sendEmail();    }    @GetMapping("/deleteFile")    public void deleteFile() {        asyncTestService.deleteFile();    }}

    结果如下:不同的业务走不同的异常处理器

    源码分析

    首先咱们从@EnableAsync入口开始看起

    @Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented//使用@Import 导入AsyncConfigurationSelector类到容器中@Import(AsyncConfigurationSelector.class) public @interface EnableAsync {//自定义异步注解Class annType = GenericTypeResolver.resolveTypeArgument(getClass(), AdviceModeImportSelector.class);Assert.state(annType != null, "Unresolvable type argument for AdviceModeImportSelector");AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);if (attributes == null) {throw new IllegalArgumentException(String.format("@%s is not present on importing class '%s' as expected",annType.getSimpleName(), importingClassMetadata.getClassName()));}//得到加了@Import注解类上的mode属性值AdviceMode adviceMode = attributes.getEnum(getAdviceModeAttributeName());//模板方法 调用子类实现的selectImports方法得到需要导入到Spring容器中的类的String[] imports = selectImports(adviceMode);if (imports == null) {throw new IllegalArgumentException("Unknown AdviceMode: " + adviceMode);}return imports;}@Nullableprotected abstract String[] selectImports(AdviceMode adviceMode);}

    由于@EnableAsync mode属性默认为AdviceMode.PROXY ,所以ProxyAsyncConfiguration类将会导入容器继续点进去看

    @Configuration(proxyBeanMethods = false)@Role(BeanDefinition.ROLE_INFRASTRUCTURE)public class ProxyAsyncConfiguration extends AbstractAsyncConfiguration {//把异步后置处理器放入容器中@Bean(name = TaskManagementConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME)@Role(BeanDefinition.ROLE_INFRASTRUCTURE)public AsyncAnnotationBeanPostProcessor asyncAdvisor() {Assert.notNull(this.enableAsync, "@EnableAsync annotation metadata was not injected");//异步后置处理器AsyncAnnotationBeanPostProcessor bpp = new AsyncAnnotationBeanPostProcessor();//把线程池和异常处理器放到后置处理器中bpp.configure(this.executor, this.exceptionHandler);//得到@EnableAsync中annotation的注解Class

上一篇:微众银行开户攻略,轻松上手,一步到位开户指南!

下一篇:怎么代理游戏服务器失败?