spring cache启动开关 EnabelCaching
@EnableAsync @SpringBootApplication(scanBasePackages = {"com.lls.asset.service"}, exclude = { DataSourceAutoConfiguration.class, MybatisPlusConfig.class }) @NacosPropertySources({ @NacosPropertySource(dataId = "ast-service", autoRefreshed = true, type = ConfigType.YAML) }) @EnableAspectJAutoProxy(exposeProxy = true) @ public class AstServiceRunApplication { public static void main(String[] args) { SpringApplication.run(AstServiceRunApplication.class, args); } }
CacheManager spi,缓存管理器,提供了访问缓存名称和缓存对象的方法。spring 本身提供了simpleCacheManager 、compositeCacheManager等管理器的实现。我们项目用的是redisCacheManager,需要配置maven如下。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
spring提供基础类AbstractCacheManager 提供了缓存管理的能力,该类根据缓存名称来获取某个缓存, ConcurrentMap<String, Cache> 这里的Cache在我们的项目里就是RedisCache ,然后在从RedisCache对象中根据 根据key获取缓存值。
public abstract class AbstractCacheManager implements CacheManager, InitializingBean { private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<>(16); //根据缓存名称获取这个缓存 public Cache getCache(String name) { Cache cache = this.cacheMap.get(name); if (cache != null) { return cache; else { // Fully synchronize now for missing cache creation... synchronized (this.cacheMap) { cache = this.cacheMap.get(name); if (cache == null) { cache = getMissingCache(name); if (cache != null) { cache = decorateCache(cache); this.cacheMap.put(name, cache); updateCacheNames(name); } } return cache; } }
spring提供的基础类AbstractValueAdaptingCache implements Cache 拥有 取出缓存对象,删除缓存的接口, AbstractValueAdaptingCache 根据key获取缓存对象的方法。lookup(value) 具体实现就是从redisCache获取
AbstractValueAdaptingCache 提供的get 方法。 public <T> T get(Object key, @Nullable Class<T> type) { Object value = fromStoreValue(lookup(key)); if (value != null && type != null && !type.isInstance(value)) { throw new IllegalStateException( "Cached value is not of required type [" + type.getName() + "]: " + value); } return (T) value; } RedisCache 提供的lookup 具体查找key,value的方法: protected Object lookup(Object key) { byte[] value = cacheWriter.get(name, createAndConvertCacheKey(key)); if (value == null) { return null; } return deserializeCacheValue(value); }
redis cache根据key获取缓存对象,之中的key就是对象的toString。因此如果key是某个object那么缓存的
的key值就是toString。