【老王读Spring AOP-6】@Async产生AOP代理的原理

前言

我们知道,@Async 是通过 Spring AOP 的方式来实现的。
前面讲了 Spring 中使用 @Transactional 的原理是通过定义 Advisor bean (BeanFactoryTransactionAttributeSourceAdvisor)的方式,让 AnnotationAwareAspectJAutoProxyCreator 帮助产生 AOP 动态代理类。

那么 @Async 的原理是不是也是定义一个 Advisor bean 呢?

这里先剧透一下:@Async 跟 @Transactional 使用 Spring AOP 的方式不太一样,@Async 是 new 一个 Advisor 来处理的,而不是定义一个 Advisor bean。

@Transactional产生AOP代理的原理请戳:https://blog.csdn.net/wang489687009/article/details/121214357

版本约定

Spring 5.3.9 (通过 SpringBoot 2.5.3 间接引入的依赖)

正文

Spring 中使用 AsyncAnnotationBeanPostProcessor 来处理 @Async 标记的类或方法,来生成相应的 AOP 代理类。

AsyncAnnotationBeanPostProcessor

AsyncAnnotationBeanPostProcessor 的类图如下:
AsyncAnnotationBeanPostProcessor

总结一个小技巧:
要看 Spring AOP 是如何实现某个特定的功能的话,就找到相应的 Advisor 是什么。
比如: 要看 @Transactional 是如何实现的,我们就可以找到 BeanFactoryTransactionAttributeSourceAdvisor .

首先找下 @Async 相应的 Advisor 是在哪里定义的:

// AsyncAnnotationBeanPostProcessor#setBeanFactory()
public void setBeanFactory(BeanFactory beanFactory) {
    super.setBeanFactory(beanFactory);

    // new 一个 AsyncAnnotationAdvisor 
    AsyncAnnotationAdvisor advisor = new AsyncAnnotationAdvisor(this.executor, this.exceptionHandler);
    if (this.asyncAnnotationType != null) {
        advisor.setAsyncAnnotationType(this.asyncAnnotationType);
    }
    advisor.setBeanFactory(beanFactory);
    this.advisor = advisor;
}

AsyncAnnotationAdvisor

对于 Advisor,我们需要关注的有两个: 一是 Pointcut;二是 Advice

AsyncAnnotationAdvisor 对应的 Pointcut

创建 Pointcut 的源码如下:

// AsyncAnnotationAdvisor#buildPointcut()
protected Pointcut buildPointcut(Set<Class<? extends Annotation>> asyncAnnotationTypes) {
    ComposablePointcut result = null;
    for (Class<? extends Annotation> asyncAnnotationType : asyncAnnotationTypes) {
        // class pointcut: 匹配类上的 @Async 注解  
        Pointcut cpc = new AnnotationMatchingPointcut(asyncAnnotationType, true);
        // method pointcut: 匹配 method 上的 @Async 注解
        Pointcut mpc = new AnnotationMatchingPointcut(null, asyncAnnotationType, true);
        if (result == null) {
            result = new ComposablePointcut(cpc);
        }
        else {
            result.union(cpc);
        }
        result = result.union(mpc);
    }
    return (result != null ? result : Pointcut.TRUE);
}

可以看出,创建出的 Pointcut 会匹配类 或者 方法上的 @Async 注解,满足匹配条件的话,就会使用相应的 Advice 来生成代理类。

AsyncAnnotationAdvisor 对应的 Advice: AnnotationAsyncExecutionInterceptor

// AsyncAnnotationAdvisor#buildAdvice()
protected Advice buildAdvice(Supplier<Executor> executor, Supplier<AsyncUncaughtExceptionHandler> exceptionHandler) {
    AnnotationAsyncExecutionInterceptor interceptor = new AnnotationAsyncExecutionInterceptor(null);
    interceptor.configure(executor, exceptionHandler);
    return interceptor;
}

AnnotationAsyncExecutionInterceptor 的实现原理

AnnotationAsyncExecutionInterceptor 是 @Async 方法实现异步执行的核心类。

// AsyncExecutionInterceptor#invoke()
public Object invoke(final MethodInvocation invocation) throws Throwable {
    Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
    Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
    final Method userDeclaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

    // 选择指定的 AsyncTaskExecutor  
    AsyncTaskExecutor executor = determineAsyncExecutor(userDeclaredMethod);
    if (executor == null) {
        throw new IllegalStateException(
                "No executor specified and no default executor set on AsyncExecutionInterceptor either");
    }

    // 将目标方法的执行封装成一个 Callable Task  
    Callable<Object> task = () -> {
        try {
            Object result = invocation.proceed();
            if (result instanceof Future) {
                return ((Future<?>) result).get();
            }
        } catch (ExecutionException ex) {
            handleError(ex.getCause(), userDeclaredMethod, invocation.getArguments());
        } catch (Throwable ex) {
            // 异常结果的处理
            handleError(ex, userDeclaredMethod, invocation.getArguments());
        }
        return null;
    };

    // 提交 task 任务到 AsyncTaskExecutor 
    return doSubmit(task, executor, invocation.getMethod().getReturnType());
}

总体来看,它的执行分为如下几步:

  1. 获取指定的 AsyncTaskExecutor
  2. 将目标方法的执行封装成一个 Callable Task
  3. 提交 task 任务到 AsyncTaskExecutor

@Async 指定异步线程池运行

@Async 可以通过 value 来指定使用哪个异步线程池来执行目标方法

相应的源码如下:

// AsyncAnnotationAdvisor#getExecutorQualifier()
protected String getExecutorQualifier(Method method) {
    // Maintainer's note: changes made here should also be made in
    // AnnotationAsyncExecutionAspect#getExecutorQualifier
    Async async = AnnotatedElementUtils.findMergedAnnotation(method, Async.class);
    if (async == null) {
        async = AnnotatedElementUtils.findMergedAnnotation(method.getDeclaringClass(), Async.class);
    }
    return (async != null ? async.value() : null);
}

@Async method 支持的返回类型

@Async method 支持 4 种返回类型: void、CompletableFuture、ListenableFuture、Future

protected Object doSubmit(Callable<Object> task, AsyncTaskExecutor executor, Class<?> returnType) {
    if (CompletableFuture.class.isAssignableFrom(returnType)) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                return task.call();
            } catch (Throwable ex) {
                throw new CompletionException(ex);
            }
        }, executor);
    } else if (ListenableFuture.class.isAssignableFrom(returnType)) {
        return ((AsyncListenableTaskExecutor) executor).submitListenable(task);
    } else if (Future.class.isAssignableFrom(returnType)) {
        return executor.submit(task);
    } else {
        executor.submit(task);
        return null;
    }
}

@Async method 返回异常结果的处理

@Async method 返回异常的话,会交给 handleError() 来处理:

// AsyncExecutionAspectSupport#handleError()
protected void handleError(Throwable ex, Method method, Object... params) throws Exception {
    if (Future.class.isAssignableFrom(method.getReturnType())) {
        ReflectionUtils.rethrowException(ex);
    } else {
        // Could not transmit the exception to the caller with default executor
        try {
            this.exceptionHandler.obtain().handleUncaughtException(ex, method, params);
        } catch (Throwable ex2) {
            logger.warn("Exception handler for async method '" + method.toGenericString() +
                    "' threw unexpected exception itself", ex2);
        }
    }
}

可以看出:

  1. 对于 method 的返回类型是 Future 及子类的话,异常会直接抛出去,也就是抛到 Future#get() 的调用处
  2. 对于 method 的返回类型是 void 的话,异常会交给内部的 AsyncUncaughtExceptionHandler 来处理

小结

@Async 是通过 AsyncAnnotationBeanPostProcessor 来产生 AOP 代理对象的。
@Async 相应的 Advisor 是 AsyncAnnotationAdvisor
真正起作用的 Advice 是 AnnotationAsyncExecutionInterceptor

@Async 可以通过 value 来指定使用的异步线程池。
@Async method 支持 4 种返回类型: void、CompletableFuture、ListenableFuture、Future


如果本文对你有所帮助,欢迎点赞收藏!

源码测试工程下载:
老王读Spring IoC源码分析&测试代码下载
老王读Spring AOP源码分析&测试代码下载

公众号后台回复:下载IoC 或者 下载AOP 可以免费下载源码测试工程…

阅读更多文章,请关注公众号: 老王学源码
gzh


系列博文:
【老王读Spring AOP-0】SpringAop引入&&AOP概念、术语介绍
【老王读Spring AOP-1】Pointcut如何匹配到 join point
【老王读Spring AOP-2】如何为 Pointcut 匹配的类生成动态代理类
【老王读Spring AOP-3】Spring AOP 执行 Pointcut 对应的 Advice 的过程
【老王读Spring AOP-4】Spring AOP 与Spring IoC 结合的过程 && ProxyFactory 解析
【老王读Spring AOP-5】@Transactional产生AOP代理的原理
【老王读Spring AOP-6】@Async产生AOP代理的原理
【Spring 源码阅读】Spring IoC、AOP 原理小总结

相关阅读:
【Spring源码三千问】Spring动态代理:什么时候使用的 cglib,什么时候使用的是 jdk proxy?
【Spring源码三千问】Advice、Advisor、Advised都是什么接口?
【Spring源码三千问】没有AspectJ,Spring中如何使用SpringAOP、@Transactional?
【Spring源码三千问】Spring AOP 中 AbstractAdvisorAutoProxyCreator、AbstractAdvisingBeanPostProcessor的区别
【Spring 源码三千问】同样是AOP代理bean,为什么@Async标记的bean循环依赖时会报错?

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老王学源码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值