Spring Cache 系列 & 0x01 開篇
Spring Cache 系列 & 0x02 組件
Spring Cache 系列 & 0x03 注解
這一篇試著講解 Spring Cache 如何加載緩存實(shí)例的。
Spring Cache 是使用動(dòng)態(tài)代理完成的芝硬,下面一步一步剖析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);
}
}
上面兩個(gè)類是演示如何使用 Spring Cache 的欺嗤;接下來對最要的類做進(jìn)一步分析交掏;
0x02 Cache 入口
0x021 EnableCaching
這個(gè)注解的表面意思是開啟緩存
沈条;也就是加載酣难、管理緩存實(shí)例的入口让虐;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
// 這里會(huì)交由 Spring 加載、實(shí)例化 Import 里的類 CachingConfigurationSelector罢荡; 可以去網(wǎng)上搜索有關(guān) 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<EnableCaching> {
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() 的配置,這里默認(rèn)是 PROXY(JDK PROXY)
switch (adviceMode) {
case PROXY:
// 我們主要介紹的是 JDK PROXY
return getProxyImports();
case ASPECTJ:
return getAspectJImports();
default:
return null;
}
}
private String[] getProxyImports() {
// 默認(rèn)加載兩個(gè)類AutoProxyRegistrar区赵、ProxyCachingConfiguration
List<String> result = new ArrayList<>(3);
result.add(AutoProxyRegistrar.class.getName());
result.add(ProxyCachingConfiguration.class.getName());
// 這里我們不介紹 JCACHE惭缰;因?yàn)樗挥绊懳覀兪褂?Spring Cache
if (jsr107Present && jcacheImplPresent) {
result.add(PROXY_JCACHE_CONFIGURATION_CLASS);
}
return StringUtils.toStringArray(result);
}
private String[] getAspectJImports() {
List<String> 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<A extends Annotation> implements ImportSelector {
// 這個(gè)常量對應(yīng)的 是 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 動(dòng)態(tài)加載 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 表示的是當(dāng)前加載的 Bean笼才;也就是 CacheConfiguration 實(shí)例漱受;
// 類 AutoProxyRegistrar 是通過 EnableCaching 注解加載的;而 EnableCaching 是在 CacheConfiguration 類上的骡送;
// 所有 annTypes 獲取的 CacheConfiguration 類型上的 注解昂羡;也就是 @Configuration、@EnableCaching
Set<String> annTypes = importingClassMetadata.getAnnotationTypes();
for (String annType : annTypes) {
AnnotationAttributes candidate = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);
if (candidate == null) {
continue;
}
// 這里獲取 EnableCaching 注解的屬性摔踱;
// 通過這里我們可以自定義注解實(shí)現(xiàn)我們自己的業(yè)務(wù)虐先;配置 mode、proxyTargetClass 兩個(gè)屬性派敷,開通 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) {
// 這里加載一個(gè)重要的類 InfrastructureAdvisorAutoProxyCreator 蛹批;
// 而這個(gè)類有一個(gè)重要的接口 InstantiationAwareBeanPostProcessor,這個(gè)接口的有一個(gè)方法 postProcessBeforeInstantiation 是在 Spring 初始化完 Bean 實(shí)例化之前調(diào)的接口篮愉;
// AOP 就是在這里對符合條件(下面會(huì)介紹怎么符合條件)的 Bean 進(jìn)行動(dòng)態(tài)代理控制
// @see org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessBeforeInstantiation 這是 InfrastructureAdvisorAutoProxyCreator 類的子類腐芍;
AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
if ((Boolean) proxyTargetClass) {
// @see org.springframework.aop.framework.DefaultAopProxyFactory#createAopProxy
// 如果沒有這個(gè),Spring 默認(rèn)使用 JDK 動(dòng)態(tài)代理
AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
return;
}
}
}
}
}
0x024 ProxyCachingConfiguration
@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class ProxyCachingConfiguration extends AbstractCachingConfiguration {
// 實(shí)例化 AOP 緩存 切面
// 如果不了解切面可以去網(wǎng)上搜索一下 AOP 介紹试躏;
@Bean(name = CacheManagementConfigUtils.CACHE_ADVISOR_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public BeanFactoryCacheOperationSourceAdvisor cacheAdvisor() {
BeanFactoryCacheOperationSourceAdvisor advisor = new BeanFactoryCacheOperationSourceAdvisor();
// 在類里轉(zhuǎn)換成切點(diǎn)猪勇,這里就是如何匹配符合條件的類;并對這些類代理
advisor.setCacheOperationSource(cacheOperationSource());
// 通知冗酿,執(zhí)行業(yè)務(wù)
advisor.setAdvice(cacheInterceptor());
if (this.enableCaching != null) {
advisor.setOrder(this.enableCaching.<Integer>getNumber("order"));
}
return advisor;
}
// 這個(gè)類里加裝解析緩存用到的 注解
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public CacheOperationSource cacheOperationSource() {
return new AnnotationCacheOperationSource();
}
// 實(shí)例化 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埠对,以及加載一個(gè)類似
CacheService
用到了那些Spring 組件;如果你熟悉了上面 EnableCaching 注解模式(Spring 4.x裁替、Spring Boot 大量使用)项玛、@Import 注解、ImportBeanDefinitionRegistrar 動(dòng)態(tài)加載 Bean 接口弱判、AOP(切面襟沮、切點(diǎn)、連接點(diǎn)、通知)开伏、BeanPostProcessor 組件膀跌、以及了解Spring 的加載過程;學(xué)習(xí) Spring Cache 不會(huì)有任何壓力固灵。
如果你已經(jīng)看過 Spring Cache 系列 & 0x01 開篇 這篇文章捅伤;你可以試著Debug InfrastructureAdvisorAutoProxyCreator#postProcessBeforeInstantiation(Class<?>, String)
方法,你就會(huì)知道如何創(chuàng)建代理類巫玻;