上文曾经讲过@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 }}@Configurationpublic class WorkPool { @Bean("WorkPool") public ThreadPoolTaskExecutor taskExecutor(){ ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); threadPoolTaskExecutor.initialize(); return threadPoolTaskExecutor; }}@Componentpublic 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异步调用。