Spring Cache 系列 & 0x02 组件

Spring Cache 系列 & 0x01 开篇
Spring Cache 系列 & 0x02 组件
Spring Cache 系列 & 0x03 注解

这一篇试着讲解 Spring Cache 如何加载缓存实例的。
Spring Cache 是使用动态代理完成的,下面一步一步剖析Spring 如何加载管理 Cache Bean 的。

0x01 需要的代码

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = {"CacheService"})
public class CacheService {

    @Cacheable(key = "#root.targetClass.getName() + '_' + #root.args[0]")
    public String get(Long value) {

        return "-1";
    }

    @CachePut(key = "#root.targetClass.getName() + '_' + #p0")
    public String update(Long value) {
        return "0";
    }

    @CacheEvict(key = "#root.targetClass.getName() + '_' + #a0")
    public void delete(Long value) {

    }
}

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleCacheErrorHandler;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CacheConfiguration {


    @Bean
    public CachingConfigurer cachingConfigurer() {
        return new CachingConfigurer() {
            @Override
            public CacheManager cacheManager() {
                return new ConcurrentMapCacheManager();
            }

            @Override
            public CacheResolver cacheResolver() {
                return null;
            }

            @Override
            public KeyGenerator keyGenerator() {
                return null;
            }

            @Override
            public CacheErrorHandler errorHandler() {
                return new SimpleCacheErrorHandler();
            }
        };
    }

    @Bean
    public CacheService cacheService() {
        return new CacheService();
    }


    public static void main(String[] args) {
        Long id = 10L;
        AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(CacheConfiguration.class);
        CacheService cacheService = app.getBean(CacheService.class);
        String s = cacheService.get(id);
        System.out.println("get: " + s);

        String update = cacheService.update(id);
        System.out.println("update: " + update);

        String s1 = cacheService.get(id);
        System.out.println("get: " + s1);
        
        cacheService.delete(id);

        String s2 = cacheService.get(id);
        System.out.println("get: " + s2);
    }

}

上面两个类是演示如何使用 Spring Cache 的;接下来对最要的类做进一步分析;

0x02 Cache 入口

0x021 EnableCaching

这个注解的表面意思是开启缓存;也就是加载、管理缓存实例的入口;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
// 这里会交由 Spring 加载、实例化 Import 里的类 CachingConfigurationSelector; 可以去网上搜索有关 Import 的用途说明;
@Import(CachingConfigurationSelector.class)
public @interface EnableCaching {
    boolean proxyTargetClass() default false;
    AdviceMode mode() default AdviceMode.PROXY;

    int order() default Ordered.LOWEST_PRECEDENCE;
}

0x022 CachingConfigurationSelector

public class CachingConfigurationSelector extends AdviceModeImportSelector {

    private static final String PROXY_JCACHE_CONFIGURATION_CLASS =
            "org.springframework.cache.jcache.config.ProxyJCacheConfiguration";

    private static final String CACHE_ASPECT_CONFIGURATION_CLASS_NAME =
            "org.springframework.cache.aspectj.AspectJCachingConfiguration";

    private static final String JCACHE_ASPECT_CONFIGURATION_CLASS_NAME =
            "org.springframework.cache.aspectj.AspectJJCacheConfiguration";


    private static final boolean jsr107Present;

    private static final boolean jcacheImplPresent;

    static {
        ClassLoader classLoader = CachingConfigurationSelector.class.getClassLoader();
        jsr107Present = ClassUtils.isPresent("javax.cache.Cache", classLoader);
        jcacheImplPresent = ClassUtils.isPresent(PROXY_JCACHE_CONFIGURATION_CLASS, classLoader);
    }

   // 重写父类方法
    @Override
    public String[] selectImports(AdviceMode adviceMode) {
            // EnableCaching#mode() 的配置,这里默认是 PROXY(JDK PROXY)
        switch (adviceMode) {
            case PROXY:
                            // 我们主要介绍的是 JDK PROXY
                return getProxyImports();
            case ASPECTJ:
                return getAspectJImports();
            default:
                return null;
        }
    }
     
    private String[] getProxyImports() {
// 默认加载两个类AutoProxyRegistrar、ProxyCachingConfiguration
        List result = new ArrayList<>(3);
        result.add(AutoProxyRegistrar.class.getName());
        result.add(ProxyCachingConfiguration.class.getName());
// 这里我们不介绍 JCACHE;因为他不影响我们使用 Spring Cache
        if (jsr107Present && jcacheImplPresent) {
            result.add(PROXY_JCACHE_CONFIGURATION_CLASS);
        }
        return StringUtils.toStringArray(result);
    }

    private String[] getAspectJImports() {
        List result = new ArrayList<>(2);
        result.add(CACHE_ASPECT_CONFIGURATION_CLASS_NAME);
        if (jsr107Present && jcacheImplPresent) {
            result.add(JCACHE_ASPECT_CONFIGURATION_CLASS_NAME);
        }
        return StringUtils.toStringArray(result);
    }

}

// 父类
public abstract class AdviceModeImportSelector implements ImportSelector {

     // 这个常量对应的 是 EnableCaching#mode() 方法
    public static final String DEFAULT_ADVICE_MODE_ATTRIBUTE_NAME = "mode";

    protected String getAdviceModeAttributeName() {
        return DEFAULT_ADVICE_MODE_ATTRIBUTE_NAME;
    }

    @Override
    public final String[] selectImports(AnnotationMetadata importingClassMetadata) {
        Class annType = GenericTypeResolver.resolveTypeArgument(getClass(), AdviceModeImportSelector.class);
        Assert.state(annType != null, "Unresolvable type argument for AdviceModeImportSelector");

        AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);
        if (attributes == null) {
            throw new IllegalArgumentException(String.format(
                    "@%s is not present on importing class '%s' as expected",
                    annType.getSimpleName(), importingClassMetadata.getClassName()));
        }
       // 获取 EnableCaching#mode() 的配置
        AdviceMode adviceMode = attributes.getEnum(getAdviceModeAttributeName());
        String[] imports = selectImports(adviceMode);
        if (imports == null) {
            throw new IllegalArgumentException("Unknown AdviceMode: " + adviceMode);
        }
        return imports;
    }

    
         // @see CachingConfigurationSelector#selectImports(AdviceMode)
    @Nullable
    protected abstract String[] selectImports(AdviceMode adviceMode);

}

0x023 AutoProxyRegistrar

// ImportBeanDefinitionRegistrar 支持 Spring 动态加载 Bean 的重要接口;
public class AutoProxyRegistrar implements ImportBeanDefinitionRegistrar {

    private final Log logger = LogFactory.getLog(getClass());
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        boolean candidateFound = false;
   // importingClassMetadata 表示的是当前加载的 Bean;也就是 CacheConfiguration 实例;
   // 类 AutoProxyRegistrar 是通过 EnableCaching 注解加载的;而 EnableCaching 是在 CacheConfiguration 类上的;
  // 所有 annTypes 获取的 CacheConfiguration 类型上的 注解;也就是 @Configuration、@EnableCaching
        Set annTypes = importingClassMetadata.getAnnotationTypes();
        for (String annType : annTypes) {
            AnnotationAttributes candidate = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);
            if (candidate == null) {
                continue;
            }
                // 这里获取 EnableCaching 注解的属性;
                // 通过这里我们可以自定义注解实现我们自己的业务;配置 mode、proxyTargetClass 两个属性,开通 AOP 的支持
            Object mode = candidate.get("mode");
            Object proxyTargetClass = candidate.get("proxyTargetClass");
            if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() &&
                    Boolean.class == proxyTargetClass.getClass()) {
                candidateFound = true;
                if (mode == AdviceMode.PROXY) {
                    // 这里加载一个重要的类 InfrastructureAdvisorAutoProxyCreator ;
                    // 而这个类有一个重要的接口 InstantiationAwareBeanPostProcessor,这个接口的有一个方法 postProcessBeforeInstantiation 是在 Spring 初始化完 Bean 实例化之前调的接口;
                   // AOP 就是在这里对符合条件(下面会介绍怎么符合条件)的 Bean 进行动态代理控制
                   // @see org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessBeforeInstantiation 这是 InfrastructureAdvisorAutoProxyCreator 类的子类;
                    AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
                    if ((Boolean) proxyTargetClass) {
                        // @see org.springframework.aop.framework.DefaultAopProxyFactory#createAopProxy
                        // 如果没有这个,Spring 默认使用 JDK 动态代理
                        AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
                        return;
                    }
                }
            }
        }
}

0x024 ProxyCachingConfiguration

@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class ProxyCachingConfiguration extends AbstractCachingConfiguration {
     // 实例化 AOP 缓存 切面
     // 如果不了解切面可以去网上搜索一下 AOP 介绍;
    @Bean(name = CacheManagementConfigUtils.CACHE_ADVISOR_BEAN_NAME)
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    public BeanFactoryCacheOperationSourceAdvisor cacheAdvisor() {
        BeanFactoryCacheOperationSourceAdvisor advisor = new BeanFactoryCacheOperationSourceAdvisor();
            // 在类里转换成切点,这里就是如何匹配符合条件的类;并对这些类代理
        advisor.setCacheOperationSource(cacheOperationSource());
           // 通知,执行业务
        advisor.setAdvice(cacheInterceptor());
        if (this.enableCaching != null) {
            advisor.setOrder(this.enableCaching.getNumber("order"));
        }
        return advisor;
    }
    // 这个类里加装解析缓存用到的 注解 
    @Bean
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    public CacheOperationSource cacheOperationSource() {
        return new AnnotationCacheOperationSource();
    }

    // 实例化 AOP 拦截器
    @Bean
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    public CacheInterceptor cacheInterceptor() {
        CacheInterceptor interceptor = new CacheInterceptor();
        interceptor.configure(this.errorHandler, this.keyGenerator, this.cacheResolver, this.cacheManager);
        interceptor.setCacheOperationSource(cacheOperationSource());
        return interceptor;
    }

}

上面介绍了如何使用Spring Cache,以及加载一个类似CacheService用到了那些Spring 组件;如果你熟悉了上面 EnableCaching 注解模式(Spring 4.x、Spring Boot 大量使用)、@Import 注解、ImportBeanDefinitionRegistrar 动态加载 Bean 接口、AOP(切面、切点、连接点、通知)、BeanPostProcessor 组件、以及了解Spring 的加载过程;学习 Spring Cache 不会有任何压力。

如果你已经看过 Spring Cache 系列 & 0x01 开篇 这篇文章;你可以试着Debug InfrastructureAdvisorAutoProxyCreator#postProcessBeforeInstantiation(Class, String) 方法,你就会知道如何创建代理类;

你可能感兴趣的:(Spring Cache 系列 & 0x02 组件)