這上一篇文章中我們熟悉了SpringBoot Cache的基本使用,接下來我們看下它的執(zhí)行流程
-
CacheAutoConfiguration 自動裝配類
根據(jù)圖中標(biāo)注,看到它引用了CachingConfigurationSelector這個類

a2.png
靜態(tài)內(nèi)部類,實現(xiàn)了 selectImports()這個方法 ,這個方法用于添加配置類
通過debugger觀察 imports[]數(shù)組,在控制臺中看到 SimpleCacheConfiguration類的配置生效
static class CacheConfigurationImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
CacheType[] types = CacheType.values();
String[] imports = new String[types.length];
for (int i = 0; i < types.length; i++) {
imports[i] = CacheConfigurations.getConfigurationClass(types[i]);
}
return imports;
}
}
-
SimpleCacheConfiguration 配置類
創(chuàng)建ConcurrentMapCacheManager對象 ,給容器注冊了CacheManage=>ConcurrentMapCacheManager
@Bean public ConcurrentMapCacheManager cacheManager() { ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(); List<String> cacheNames = this.cacheProperties.getCacheNames(); if (!cacheNames.isEmpty()) { cacheManager.setCacheNames(cacheNames); } return this.customizerInvoker.customize(cacheManager); }
- ConcurrentMapCacheManager 類
[圖片上傳失敗...(image-2a6db9-1530901912375)]

b2.png
找到getCache()這個方法,根據(jù)方法名就可以知道這是獲取緩存的方法
@Override
@Nullable
public Cache getCache(String name) {
Cache cache = this.cacheMap.get(name);
if (cache == null && this.dynamic) {//判斷是否為null
synchronized (this.cacheMap) {//加鎖
cache = this.cacheMap.get(name);
if (cache == null) {
cache = createConcurrentMapCache(name);//保存至createConcurrentMapCache
this.cacheMap.put(name, cache);
}
}
}
return cache;
}
createConcurrentMapCache方法
protected Cache createConcurrentMapCache(String name) {
SerializationDelegate actualSerialization = (isStoreByValue() ? this.serialization : null);
return new ConcurrentMapCache(name, new ConcurrentHashMap<>(256),
isAllowNullValues(), actualSerialization);
}
回到ConcurrentHashMap類,找到lookup()這個方法 ,這個緩存Key是怎么得到的呢,對這個方法打斷點,看它的調(diào)用棧
@Override
@Nullable
protected Object lookup(Object key) {
return this.store.get(key);
}

e2.png
進入generatorKey()這個方法

c3.png
找到這個接口,是不是有了熟悉的感覺,這就是自定義主鍵生成策略需要實現(xiàn)的接口

d2.png
致此,整合流程也就走完了,這里增加一點內(nèi)容關(guān)于@Caching
這個注解相當(dāng)于把 @CachePut、 @CacheEvict、@Cacheable這三個注解組合在一起,增加了靈活性,使用與之前類似,就不展開了

f2.png
如理解有誤,請指正