源码_Springboot与Cache 缓存工作原理

缓存工作原理

1.如果往Springboot中引入Cache模块,那么缓存模块就会生效,引入缓存的自动配置类CacheAutoConfiguration

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(CacheManager.class)
@ConditionalOnBean(CacheAspectSupport.class)
@ConditionalOnMissingBean(value = CacheManager.class, name = "cacheResolver")
@EnableConfigurationProperties(CacheProperties.class)
@AutoConfigureAfter({ CouchbaseAutoConfiguration.class, HazelcastAutoConfiguration.class,
		HibernateJpaAutoConfiguration.class, RedisAutoConfiguration.class })
//1.给容器中导入CacheConfigurationImportSelector.class
@Import({ CacheConfigurationImportSelector.class, CacheManagerEntityManagerFactoryDependsOnPostProcessor.class })
public class CacheAutoConfiguration {
/**
	 * 2.调用该方法给容器导入一些需要的组件
	 */
	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;
			//imports 缓存的配置类:
			/*org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration
			org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration
			org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
			org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration
			org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration
			org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration
			org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration
			org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration
			org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration
			org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration*/
		}
	}
}

2.在 application.properties 中添加 debug=true 在debug的时候打开自动配置报告
看看哪个配置类默认生效
在这里插入图片描述
3.SimpleCacheConfiguration:给容器中注册了一个cacheManager(ConcurrentMapCacheManager)

@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(CacheManager.class)
@Conditional(CacheCondition.class)
class SimpleCacheConfiguration {

	@Bean
	ConcurrentMapCacheManager cacheManager(CacheProperties cacheProperties,
			CacheManagerCustomizers cacheManagerCustomizers) {
		ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager();
		List<String> cacheNames = cacheProperties.getCacheNames();
		if (!cacheNames.isEmpty()) {
			cacheManager.setCacheNames(cacheNames);
		}
		return cacheManagerCustomizers.customize(cacheManager);
	}

}

4.分析ConcurrentMapCacheManager

public interface CacheManager {

	@Nullable
	Cache getCache(String name);

	Collection<String> getCacheNames();

}
//!ConcurrentMapCacheManager 实现CacheManager,可以重写CacheManager的getCache方法根据缓存的名字拿到一个缓存组件
public class ConcurrentMapCacheManager implements CacheManager, BeanClassLoaderAware {

//!该hashmap中保存了缓存的名字和缓存的组件
private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<>(16);

	@Override
	@Nullable
	public Cache getCache(String name) {
	//!从该hasnmap中根据缓存的名字拿到缓存的组件
		Cache cache = this.cacheMap.get(name);
		//!如果缓存组件为null就锁一下再次从该map中获取缓存组件
		if (cache == null && this.dynamic) {
			synchronized (this.cacheMap) {
				cache = this.cacheMap.get(name);
				//!如果还是为null就调用createConcurrentMapCache(name)方法创建该ConcurrentMapCache类型的缓存
				if (cache == null) {
					cache = createConcurrentMapCache(name);
					//!将创建出来的缓存组件放入cacheMap中
					this.cacheMap.put(name, cache);
				}
			}
		}
		return cache;
	}

	protected Cache createConcurrentMapCache(String name) {
		SerializationDelegate actualSerialization = (isStoreByValue() ? 	this.serialization : null);
		//!调用ConcurrentMapCache创建缓存对象
		return new ConcurrentMapCache(name, new ConcurrentHashMap<>(256), isAllowNullValues(), actualSerialization);
	}
	
}

5.分析ConcurrentMapCache

public class ConcurrentMapCache extends AbstractValueAdaptingCache {

	private final String name;

	//!store的作用是将数据保存到ConcurrentMap中
	private final ConcurrentMap<Object, Object> store;

	@Nullable
	private final SerializationDelegate serialization;

	protected ConcurrentMapCache(String name, ConcurrentMap<Object, Object> store,
		boolean allowNullValues, @Nullable SerializationDelegate serialization) {

		super(allowNullValues);
		Assert.notNull(name, "Name must not be null");
		Assert.notNull(store, "Store must not be null");
		this.name = name;
		this.store = store;
		this.serialization = serialization;
	}

	//!从缓存中查询
	@Override
	@Nullable
	protected Object lookup(Object key) {
		return this.store.get(key);
	}
	
	//!放入缓存
	@Override
	public void put(Object key, @Nullable Object value) {
		this.store.put(key, toStoreValue(value));
	}

	
}
*   运行流程:
 *   @Cacheable:
 *   1、方法运行之前,先去查询Cache(缓存组件),按照cacheNames指定的名字获取;
 *      (CacheManager先获取相应的缓存),第一次获取缓存如果没有Cache组件会自动创建。
 *   2、去Cache中查找缓存的内容,使用一个key,默认就是方法的参数;
 *      key是按照某种策略生成的;默认是使用keyGenerator生成的,默认使用SimpleKeyGenerator生成key;
 *      SimpleKeyGenerator生成key的默认策略;
 *                  如果没有参数;key=new SimpleKey();
 *                  如果有一个参数:key=参数的值
 *                  如果有多个参数:key=new SimpleKey(params);
 *   3、没有查到缓存就调用目标方法;
 *   4、将目标方法返回的结果,放进缓存中
public abstract class CacheAspectSupport extends AbstractCacheInvoker
		implements BeanFactoryAware, InitializingBean, SmartInitializingSingleton {
		//!key的生成
	private SingletonSupplier<KeyGenerator> keyGenerator = SingletonSupplier.of(SimpleKeyGenerator::new);
	
	}

接口KeyGenerator

@FunctionalInterface
public interface KeyGenerator {

	Object generate(Object target, Method method, Object... params);

}

实现类SimpleKeyGenerator :生成key

public class SimpleKeyGenerator implements KeyGenerator {

	@Override
	public Object generate(Object target, Method method, Object... params) {
		return generateKey(params);
	}
		public static Object generateKey(Object... params) {
		if (params.length == 0) {
			return SimpleKey.EMPTY;
		}
		if (params.length == 1) {
			Object param = params[0];
			if (param != null && !param.getClass().isArray()) {
				return param;
			}
		}
		return new SimpleKey(params);
	}

}
}
 *   核心:
 *      1)、使用CacheManager【ConcurrentMapCacheManager】按照名字得到Cache【ConcurrentMapCache】组件
 *      2)、key使用keyGenerator生成的,默认是SimpleKeyGenerator
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值