這篇文章帶給大家的內容是關於Spring Boot快取原始碼的理解,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。
專案裡面要增加一個應用程式緩存,原本想著要怎麼怎麼來整合ehcache和springboot,做好準備配置這個配置那個,結果只需要做三件事:
pom依賴
寫好一個ehcache的設定檔
在boot的application上加上註解@EnableCaching.
這就完事了,是不是很魔幻。
pom依賴
<dependency> <groupid>net.sf.ehcache</groupid> <artifactid>ehcache</artifactid> <version>2.10.5</version> </dependency>
設定檔
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <!-- 设定缓存的默认数据过期策略 --> <defaultcache></defaultcache> </ehcache>
應用程式上加上EnableCaching註解
#@SpringBootApplication @EnableCaching public class EhCacheApplication { public static void main(String[] args) { SpringApplication.run(EhCacheApplication.class, args); } }
然後就可以在程式碼裡面使用cache註解了,像這樣。
@CachePut(value = "fish-ehcache", key = "#person.id") public Person save(Person person) { System.out.println("为id、key为:" + person.getId() + "数据做了缓存"); return person; } @CacheEvict(value = "fish-ehcache") public void remove(Long id) { System.out.println("删除了id、key为" + id + "的数据缓存"); } @Cacheable(value = "fish-ehcache", key = "#person.id") public Person findOne(Person person) { findCount.incrementAndGet(); System.out.println("为id、key为:" + person.getId() + "数据做了缓存"); return person; }
很方便對不對。下面,我們就來挖一挖,看看spring是怎麼做到的。主要分成兩部分,一是啟動的時候做了什麼,二是運行的時候做了什麼,三是和第三方緩存組件的適配
啟動的時候做了什麼、
這個得從@EnableCaching標籤開始,在使用快取功能時,在springboot的Application啟動類別上需要添加註解@EnableCaching,這個標籤引入了
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({CachingConfigurationSelector.class}) public @interface EnableCaching { boolean proxyTargetClass() default false; AdviceMode mode() default AdviceMode.PROXY; int order() default 2147483647; }
引入了CachingConfigurationSelector類,這個類別便開啟了快取功能的配置。這個類別加入了AutoProxyRegistrar.java,ProxyCachingConfiguration.java兩個類別。
AutoProxyRegistrar : 實作了ImportBeanDefinitionRegistrar介面。這裡看不懂,還需要繼續學習。
ProxyCachingConfiguration : 是一個設定類,產生了BeanFactoryCacheOperationSourceAdvisor,CacheOperationSource,和CacheInterceptor這三個bean。
CacheOperationSource封裝了cache方法簽章註解的解析工作,形成CacheOperation的集合。 CacheInterceptor使用該集合過濾執行快取處理。解析快取註解的類別是SpringCacheAnnotationParser,其主要方法如下
/** 由CacheOperationSourcePointcut作为注解切面,会解析 SpringCacheAnnotationParser.java 扫描方法签名,解析被缓存注解修饰的方法,将生成一个CacheOperation的子类并将其保存到一个数组中去 **/ protected Collection<cacheoperation> parseCacheAnnotations(SpringCacheAnnotationParser.DefaultCacheConfig cachingConfig, AnnotatedElement ae) { Collection<cacheoperation> ops = null; //找@cacheable注解方法 Collection<cacheable> cacheables = AnnotatedElementUtils.getAllMergedAnnotations(ae, Cacheable.class); if (!cacheables.isEmpty()) { ops = this.lazyInit(ops); Iterator var5 = cacheables.iterator(); while(var5.hasNext()) { Cacheable cacheable = (Cacheable)var5.next(); ops.add(this.parseCacheableAnnotation(ae, cachingConfig, cacheable)); } } //找@cacheEvict注解的方法 Collection<cacheevict> evicts = AnnotatedElementUtils.getAllMergedAnnotations(ae, CacheEvict.class); if (!evicts.isEmpty()) { ops = this.lazyInit(ops); Iterator var12 = evicts.iterator(); while(var12.hasNext()) { CacheEvict evict = (CacheEvict)var12.next(); ops.add(this.parseEvictAnnotation(ae, cachingConfig, evict)); } } //找@cachePut注解的方法 Collection<cacheput> puts = AnnotatedElementUtils.getAllMergedAnnotations(ae, CachePut.class); if (!puts.isEmpty()) { ops = this.lazyInit(ops); Iterator var14 = puts.iterator(); while(var14.hasNext()) { CachePut put = (CachePut)var14.next(); ops.add(this.parsePutAnnotation(ae, cachingConfig, put)); } } Collection<caching> cachings = AnnotatedElementUtils.getAllMergedAnnotations(ae, Caching.class); if (!cachings.isEmpty()) { ops = this.lazyInit(ops); Iterator var16 = cachings.iterator(); while(var16.hasNext()) { Caching caching = (Caching)var16.next(); Collection<cacheoperation> cachingOps = this.parseCachingAnnotation(ae, cachingConfig, caching); if (cachingOps != null) { ops.addAll(cachingOps); } } } return ops; }</cacheoperation></caching></cacheput></cacheevict></cacheable></cacheoperation></cacheoperation>
解析Cachable,Caching,CachePut,CachEevict 這四個註解對應的方法都保存到了Collection
執行方法時做了什麼
執行的時候,主要使用了CacheInterceptor類別。
public class CacheInterceptor extends CacheAspectSupport implements MethodInterceptor, Serializable { public CacheInterceptor() { } public Object invoke(final MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); CacheOperationInvoker aopAllianceInvoker = new CacheOperationInvoker() { public Object invoke() { try { return invocation.proceed(); } catch (Throwable var2) { throw new ThrowableWrapper(var2); } } }; try { return this.execute(aopAllianceInvoker, invocation.getThis(), method, invocation.getArguments()); } catch (ThrowableWrapper var5) { throw var5.getOriginal(); } } }
這個攔截器繼承了CacheAspectSupport類別和MethodInterceptor介面。其中CacheAspectSupport封裝了主要的邏輯。比如下面這段。
/** CacheAspectSupport.java 执行@CachaEvict @CachePut @Cacheable的主要逻辑代码 **/ private Object execute(final CacheOperationInvoker invoker, Method method, CacheAspectSupport.CacheOperationContexts contexts) { if (contexts.isSynchronized()) { CacheAspectSupport.CacheOperationContext context = (CacheAspectSupport.CacheOperationContext)contexts.get(CacheableOperation.class).iterator().next(); if (this.isConditionPassing(context, CacheOperationExpressionEvaluator.NO_RESULT)) { Object key = this.generateKey(context, CacheOperationExpressionEvaluator.NO_RESULT); Cache cache = (Cache)context.getCaches().iterator().next(); try { return this.wrapCacheValue(method, cache.get(key, new Callable<object>() { public Object call() throws Exception { return CacheAspectSupport.this.unwrapReturnValue(CacheAspectSupport.this.invokeOperation(invoker)); } })); } catch (ValueRetrievalException var10) { throw (ThrowableWrapper)var10.getCause(); } } else { return this.invokeOperation(invoker); } } else { /** 执行@CacheEvict的逻辑,这里是当beforeInvocation为true时清缓存 **/ this.processCacheEvicts(contexts.get(CacheEvictOperation.class), true, CacheOperationExpressionEvaluator.NO_RESULT); //获取命中的缓存对象 ValueWrapper cacheHit = this.findCachedItem(contexts.get(CacheableOperation.class)); List<cacheaspectsupport.cacheputrequest> cachePutRequests = new LinkedList(); if (cacheHit == null) { //如果没有命中,则生成一个put的请求 this.collectPutRequests(contexts.get(CacheableOperation.class), CacheOperationExpressionEvaluator.NO_RESULT, cachePutRequests); } Object cacheValue; Object returnValue; /** 如果没有获得缓存对象,则调用业务方法获得返回对象,hasCachePut会检查exclude的情况 **/ if (cacheHit != null && cachePutRequests.isEmpty() && !this.hasCachePut(contexts)) { cacheValue = cacheHit.get(); returnValue = this.wrapCacheValue(method, cacheValue); } else { returnValue = this.invokeOperation(invoker); cacheValue = this.unwrapReturnValue(returnValue); } this.collectPutRequests(contexts.get(CachePutOperation.class), cacheValue, cachePutRequests); Iterator var8 = cachePutRequests.iterator(); while(var8.hasNext()) { CacheAspectSupport.CachePutRequest cachePutRequest = (CacheAspectSupport.CachePutRequest)var8.next(); /** 执行cachePut请求,将返回对象放到缓存中 **/ cachePutRequest.apply(cacheValue); } /** 执行@CacheEvict的逻辑,这里是当beforeInvocation为false时清缓存 **/ this.processCacheEvicts(contexts.get(CacheEvictOperation.class), false, cacheValue); return returnValue; } }</cacheaspectsupport.cacheputrequest></object>
上面的程式碼片段比較核心,都是cache的內容,對於aop的源碼,這裡不詳細展開,應該單起一篇文章進行研究。主要的類別和介面都在spring的context中,org.springframework.cache套件中。
和第三方快取元件的適配
透過以上的分析,知道了spring cache功能的來龍去脈,下面需要分析的是,為什麼只需要maven聲明一下依賴,spring boot 就可以自動就適配了.
在上面的執行方法中,我們看到了cachePutRequest.apply(cacheValue) ,這裡會操作緩存,CachePutRequest是CacheAspectSupport的內部類別。
private class CachePutRequest { private final CacheAspectSupport.CacheOperationContext context; private final Object key; public CachePutRequest(CacheAspectSupport.CacheOperationContext context, Object key) { this.context = context; this.key = key; } public void apply(Object result) { if (this.context.canPutToCache(result)) { //从context中获取cache实例,然后执行放入缓存的操作 Iterator var2 = this.context.getCaches().iterator(); while(var2.hasNext()) { Cache cache = (Cache)var2.next(); CacheAspectSupport.this.doPut(cache, this.key, result); } } } }
Cache是一個標準接口,其中EhCacheCache就是EhCache的實作類別。這裡就是SpringBoot和Ehcache之間關聯的部分,那麼context中的cache列表是什麼時候產生的呢。答案是CacheAspectSupport的getCaches方法
protected Collection extends Cache> getCaches(CacheOperationInvocationContext<cacheoperation> context, CacheResolver cacheResolver) { Collection extends Cache> caches = cacheResolver.resolveCaches(context); if (caches.isEmpty()) { throw new IllegalStateException("No cache could be resolved for '" + context.getOperation() + "' using resolver '" + cacheResolver + "'. At least one cache should be provided per cache operation."); } else { return caches; } }</cacheoperation>
而取得cache是在每次進行進行快取作業的時候執行。可以看一下呼叫堆疊
看起來有點離題,拉回來... 在spring-boot-autoconfigure套件裡,有所有自動組裝相關的類別。這裡有個EhcacheCacheConfiguration類別 ,如下
@Configuration @ConditionalOnClass({Cache.class, EhCacheCacheManager.class}) @ConditionalOnMissingBean({CacheManager.class}) @Conditional({CacheCondition.class, EhCacheCacheConfiguration.ConfigAvailableCondition.class}) class EhCacheCacheConfiguration { ...... static class ConfigAvailableCondition extends ResourceCondition { ConfigAvailableCondition() { super("EhCache", "spring.cache.ehcache", "config", new String[]{"classpath:/ehcache.xml"}); } } }
這裡會直接判斷類別路徑下是否有ehcache.xml檔
#以上是Spring Boot快取原始碼的理解的詳細內容。更多資訊請關注PHP中文網其他相關文章!