这里主要讲的spring怎么实现@async进行处理的:
xml配置如下:
<!-- 任务执行器 -->
<task:executor id="executor" pool-size="5"/>
<!--开启注解调度支持 @Async-->
<task:annotation-driven executor="executor" proxy-target-class="true"/>
//spring对@Async注册了一个beanProcessor来对对象进行拦截,并生成一个新的代理对象 或 将“处理@Async注解的advisor”加入到对象拦截器调用链中
public class AsyncAnnotationBeanPostProcessor extends AbstractAdvisingBeanPostProcessor implements BeanFactoryAware {
private Class<? extends Annotation> asyncAnnotationType;
//执行器
private Executor executor;
public AsyncAnnotationBeanPostProcessor() {
setBeforeExistingAdvisors(true);
}
public void setAsyncAnnotationType(Class<? extends Annotation> asyncAnnotationType) {
Assert.notNull(asyncAnnotationType, "'asyncAnnotationType' must not be null");
this.asyncAnnotationType = asyncAnnotationType;
}
public void setExecutor(Executor executor) {
this.executor = executor;
}
public void setBeanFactory(BeanFactory beanFactory) {
AsyncAnnotationAdvisor advisor = (this.executor != null ? new AsyncAnnotationAdvisor(this.executor) : new AsyncAnnotationAdvisor());
if (this.asyncAnnotationType != null) {
advisor.setAsyncAnnotationType(this.asyncAnnotationType);
}
advisor.setBeanFactory(beanFactory);
this.advisor = advisor;
}
}
//处理拦截对象,并将处理@Async 注解的 advisor加入到目标对象拦截器调用链中
public abstract class AbstractAdvisingBeanPostProcessor extends ProxyConfig
implements BeanPostProcessor, BeanClassLoaderAware, Ordered {
protected Advisor advisor;
protected boolean beforeExistingAdvisors = false;
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
private int order = Ordered.LOWEST_PRECEDENCE;
private final Map<Class<?>, Boolean> eligibleBeans = new ConcurrentHashMap<Class<?>, Boolean>(64);
public void setBeforeExistingAdvisors(boolean beforeExistingAdvisors) {
this.beforeExistingAdvisors = beforeExistingAdvisors;
}
public void setBeanClassLoader(ClassLoader beanClassLoader) {
this.beanClassLoader = beanClassLoader;
}
public void setOrder(int order) {
this.order = order;
}
public int getOrder() {
return this.order;
}
public Object postProcessBeforeInitialization(Object bean, String beanName) {
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof AopInfrastructureBean) { //获取AOP相关类
return bean;
}
//当前对象已经拥有一条调用拦截链,则添加我们自己的调用链
if (bean instanceof Advised) {
Advised advised = (Advised) bean;
if (!advised.isFrozen() && isEligible(AopUtils.getTargetClass(bean))) {
if (this.beforeExistingAdvisors) {
advised.addAdvisor(0, this.advisor);
}
else {
advised.addAdvisor(this.advisor);
}
return bean;
}
}
//是否满足条件,本质是调用AsyncAnnotationAdvisor的pointcut的mathes()
if (isEligible(bean, beanName)) {
ProxyFactory proxyFactory = new ProxyFactory(bean);
// Copy our properties (proxyTargetClass etc) inherited from ProxyConfig.
proxyFactory.copyFrom(this);
proxyFactory.addAdvisor(this.advisor);
return proxyFactory.getProxy(this.beanClassLoader);
}
// No async proxy needed.
return bean;
}
protected boolean isEligible(Object bean, String beanName) {
return isEligible(bean.getClass());
}
protected boolean isEligible(Class<?> targetClass) {
Boolean eligible = this.eligibleBeans.get(targetClass);
if (eligible != null) {
return eligible;
}
eligible = AopUtils.canApply(this.advisor, targetClass);
this.eligibleBeans.put(targetClass, eligible);
return eligible;
}
}
处理@Async注解的advisor源码
public class AsyncAnnotationAdvisor extends AbstractPointcutAdvisor implements BeanFactoryAware {
private Advice advice;
private Pointcut pointcut;
public AsyncAnnotationAdvisor() {
this(new SimpleAsyncTaskExecutor());
}
@SuppressWarnings("unchecked")
public AsyncAnnotationAdvisor(Executor executor) {
Set<Class<? extends Annotation>> asyncAnnotationTypes = new LinkedHashSet<Class<? extends Annotation>>(2);
asyncAnnotationTypes.add(Async.class);
try {
asyncAnnotationTypes.add((Class<? extends Annotation>)
ClassUtils.forName("javax.ejb.Asynchronous", AsyncAnnotationAdvisor.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
}
//初始化通知
this.advice = buildAdvice(executor);
//初始化切点
this.pointcut = buildPointcut(asyncAnnotationTypes);
}
public void setTaskExecutor(Executor executor) {
this.advice = buildAdvice(executor);
}
public void setAsyncAnnotationType(Class<? extends Annotation> asyncAnnotationType) {
Assert.notNull(asyncAnnotationType, "'asyncAnnotationType' must not be null");
Set<Class<? extends Annotation>> asyncAnnotationTypes = new HashSet<Class<? extends Annotation>>();
asyncAnnotationTypes.add(asyncAnnotationType);
this.pointcut = buildPointcut(asyncAnnotationTypes);
}
public void setBeanFactory(BeanFactory beanFactory) {
if (this.advice instanceof BeanFactoryAware) {
((BeanFactoryAware) this.advice).setBeanFactory(beanFactory);
}
}
public Advice getAdvice() {
return this.advice;
}
public Pointcut getPointcut() {
return this.pointcut;
}
protected Advice buildAdvice(Executor executor) {
//初始化@Async的拦截器,并指定executor
return new AnnotationAsyncExecutionInterceptor(executor);
}
protected Pointcut buildPointcut(Set<Class<? extends Annotation>> asyncAnnotationTypes) {
ComposablePointcut result = null;
for (Class<? extends Annotation> asyncAnnotationType : asyncAnnotationTypes) {
Pointcut cpc = new AnnotationMatchingPointcut(asyncAnnotationType, true);
Pointcut mpc = AnnotationMatchingPointcut.forMethodAnnotation(asyncAnnotationType);
if (result == null) {
result = new ComposablePointcut(cpc).union(mpc);
}
else {
result.union(cpc).union(mpc);
}
}
return result;
}
}
将同步转成异步执行过程如下:
public class AnnotationAsyncExecutionInterceptor extends AsyncExecutionInterceptor {
//缓存 方法对应的executor
private final Map<Method, AsyncTaskExecutor> executors = new ConcurrentHashMap<Method, AsyncTaskExecutor>(16);
private Executor defaultExecutor;
private BeanFactory beanFactory;
//初始化方法,构造器
public AnnotationAsyncExecutionInterceptor(Executor defaultExecutor) {
super(defaultExecutor);
}
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);
//获取到桥接方法对应的实际的方法
specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
//确定executor
AsyncTaskExecutor executor = determineAsyncExecutor(specificMethod);
if (executor == null) {
throw new IllegalStateException(
"No executor specified and no default executor set on AsyncExecutionInterceptor either");
}
//将调用链包装Callable对象,置入executor中
Future<?> result = executor.submit(
new Callable<Object>() {
public Object call() throws Exception {
try {
Object result = invocation.proceed();
if (result instanceof Future) {
return ((Future<?>) result).get();
}
}
catch (Throwable ex) {
ReflectionUtils.rethrowException(ex);
}
return null;
}
});
if (Future.class.isAssignableFrom(invocation.getMethod().getReturnType())) {
return result;
}
else {
return null;
}
}
//获取executor对象
protected AsyncTaskExecutor determineAsyncExecutor(Method method) {
AsyncTaskExecutor executor = this.executors.get(method);
if (executor == null) { //获取缓存
Executor executorToUse = this.defaultExecutor;
//获取qualifier
String qualifier = getExecutorQualifier(method);
if (StringUtils.hasLength(qualifier)) { //具有qualifier
Assert.notNull(this.beanFactory, "BeanFactory must be set on " + getClass().getSimpleName() +
" to access qualified executor '" + qualifier + "'");
//查找指定Executor
executorToUse = BeanFactoryAnnotationUtils.qualifiedBeanOfType(
this.beanFactory, Executor.class, qualifier);
}
else if (executorToUse == null) {
return null;
}
//将executor包装成AsyncTaskExecutor
executor = (executorToUse instanceof AsyncTaskExecutor ?
(AsyncTaskExecutor) executorToUse : new TaskExecutorAdapter(executorToUse));
this.executors.put(method, executor);
}
return executor;
}
@Override
protected String getExecutorQualifier(Method method) { //获取qualifier
//获取方法注解@Async
Async async = AnnotationUtils.findAnnotation(method, Async.class);
if (async == null) {
//获取类注解@Async
async = AnnotationUtils.findAnnotation(method.getDeclaringClass(), Async.class);
}
return (async != null ? async.value() : null);
}
}