上文曾经讲过 @EnableAsync 的 bean 构建过程,这里持续合成 @Async 执行过程,以及 spring 的 AOP 调用过程。
先上 demo
public class ApiGatewayApplication {public static void main(String[] args) {SpringApplication.run(ApiGatewayApplication.class, args);
AsyncTest test = BeanUtils.getBean("asyncTest");
test.test();//1}
}
@Configuration
public class WorkPool {@Bean("WorkPool")
public ThreadPoolTaskExecutor taskExecutor(){ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
}
@Component
public class AsyncTest {
@Async
public void test() {System.out.printf("test");
}
}
1、这一步是上面的重点,底层是怎么调用。
private static class DynamicAdvisedInterceptor implements MethodInterceptor, Serializable {
@Nullable
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
Object retVal;
if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = methodProxy.invoke(target, argsToUse);//2
} else {retVal = (new CglibAopProxy.CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy)).proceed();//3}
}
2、如果没有 AOP 行为,间接调用原 bean。
3、如果有 AOP 行为,结构一个 Cglib 的 CglibMethodInvocation 办法回调对象。
public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Cloneable {public Object proceed() throws Throwable {Object interceptorOrInterceptionAdvice = this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {InterceptorAndDynamicMethodMatcher dm = (InterceptorAndDynamicMethodMatcher)interceptorOrInterceptionAdvice;
Class<?> targetClass = this.targetClass != null ? this.targetClass : this.method.getDeclaringClass();
return dm.methodMatcher.matches(this.method, targetClass, this.arguments) ? dm.interceptor.invoke(this) : this.proceed();} else {return ((MethodInterceptor)interceptorOrInterceptionAdvice).invoke(this);//4
}
}
}
4、找到 AsyncExecutionInterceptor 执行器
public class AsyncExecutionInterceptor extends AsyncExecutionAspectSupport implements MethodInterceptor, Ordered {
@Nullable
public Object invoke(MethodInvocation invocation) throws Throwable {return this.doSubmit(task, executor, invocation.getMethod().getReturnType());//4
}
public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport implements AsyncListenableTaskExecutor, SchedulingTaskExecutor {public <T> Future<T> submit(Callable<T> task) { //5
ThreadPoolExecutor executor = this.getThreadPoolExecutor();
try {return executor.submit(task);
} catch (RejectedExecutionException var4) {throw new TaskRejectedException("Executor [" + executor + "] did not accept task:" + task, var4);
}
}
}
4、通过 doSubmit 将工作发给 TaskExecutor,实现 Async 异步的性能。
5、ThreadPoolTaskExecutor 就是在 demo 中定义的 WorkPool。
最终实现 Asyn 异步调用。