栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring cache 简单原理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring cache 简单原理

  • 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如下。


        org.springframework.boot
        spring-boot-starter-data-redis
spring提供基础类AbstractCacheManager 提供了缓存管理的能力,该类根据缓存名称来获取某个缓存,
ConcurrentMap 这里的Cache在我们的项目里就是RedisCache ,然后在从RedisCache对象中根据
根据key获取缓存值。


public abstract class AbstractCacheManager implements CacheManager, InitializingBean {
  private final ConcurrentMap 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 get(Object key, @Nullable Class 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。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/237075.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号