上文已经讲过@EnableAsync的bean构建过程,这里继续讲解@Async执行过程。@Async执行过程是spring的一个AOP调用过程。

代码

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、调用@Async修饰的方法。
(1)如果没有AOP行为,直接调用原bean。
(2)如果有AOP行为,构造一个 Cglib的CglibMethodInvocation对象并触发。


    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);//(1)
                } else {
                    retVal = (new CglibAopProxy.CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy)).proceed();//(2)
                } 
}

2、通过@Async注解,找到AsyncExecutionInterceptor执行器

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);//2
            }
        }
    }

3、通过doSubmit将任务发给TaskExecutor,实现Async异步的功能。其中,ThreadPoolTaskExecutor就是在demo中定义的WorkPool。

public class AsyncExecutionInterceptor extends AsyncExecutionAspectSupport implements MethodInterceptor, Ordered {
 @Nullable
    public Object invoke(MethodInvocation invocation) throws Throwable {

 return this.doSubmit(task, executor, invocation.getMethod().getReturnType()); 
 }

 public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport implements AsyncListenableTaskExecutor, SchedulingTaskExecutor {
public <T> Future<T> submit(Callable<T> task) { //3
        ThreadPoolExecutor executor = this.getThreadPoolExecutor();

        try {
            return executor.submit(task);
        } catch (RejectedExecutionException var4) {
            throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, var4);
        }
    }
 }

实现Asyn异步调用。


一句话
12 声望1 粉丝