SpringBoot - Spring缓存默认配置与运行流程

简介: SpringBoot - Spring缓存默认配置与运行流程

【1】CacheAutoConfiguration

在SpringBoot中,Cache的自动配置类,源码如下。

/**
 * {@link EnableAutoConfiguration Auto-configuration} for the cache abstraction. Creates a
 * {@link CacheManager} if necessary when caching is enabled via {@link EnableCaching}.
 * <p>
 * Cache store can be auto-detected or specified explicitly via configuration.
 *
 * @author Stephane Nicoll
 * @since 1.3.0
 * @see EnableCaching
 */
@Configuration
@ConditionalOnClass(CacheManager.class)
@ConditionalOnBean(CacheAspectSupport.class)
@ConditionalOnMissingBean(value = CacheManager.class, name = "cacheResolver")
@EnableConfigurationProperties(CacheProperties.class)
@AutoConfigureBefore(HibernateJpaAutoConfiguration.class)
@AutoConfigureAfter({ CouchbaseAutoConfiguration.class, HazelcastAutoConfiguration.class,
    RedisAutoConfiguration.class })
@Import(CacheConfigurationImportSelector.class)
public class CacheAutoConfiguration {
  static final String VALIDATOR_BEAN_NAME = "cacheAutoConfigurationValidator";
  @Bean
  @ConditionalOnMissingBean
  public CacheManagerCustomizers cacheManagerCustomizers(
      ObjectProvider<List<CacheManagerCustomizer<?>>> customizers) {
    return new CacheManagerCustomizers(customizers.getIfAvailable());
  }
  @Bean
  @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  public static CacheManagerValidatorPostProcessor cacheAutoConfigurationValidatorPostProcessor() {
    return new CacheManagerValidatorPostProcessor();
  }
  @Bean(name = VALIDATOR_BEAN_NAME)
  public CacheManagerValidator cacheAutoConfigurationValidator() {
    return new CacheManagerValidator();
  }
  @Configuration
  @ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class)
  @ConditionalOnBean(AbstractEntityManagerFactoryBean.class)
  protected static class CacheManagerJpaDependencyConfiguration
      extends EntityManagerFactoryDependsOnPostProcessor {
    public CacheManagerJpaDependencyConfiguration() {
      super("cacheManager");
    }
  }
  /**
   * {@link BeanFactoryPostProcessor} to ensure that the {@link CacheManagerValidator}
   * is triggered before {@link CacheAspectSupport} but without causing early
   * instantiation.
   */
  static class CacheManagerValidatorPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
        throws BeansException {
      for (String name : beanFactory.getBeanNamesForType(CacheAspectSupport.class,
          false, false)) {
        BeanDefinition definition = beanFactory.getBeanDefinition(name);
        definition.setDependsOn(
            append(definition.getDependsOn(), VALIDATOR_BEAN_NAME));
      }
    }
    private String[] append(String[] array, String value) {
      String[] result = new String[array == null ? 1 : array.length + 1];
      if (array != null) {
        System.arraycopy(array, 0, result, 0, array.length);
      }
      result[result.length - 1] = value;
      return result;
    }
  }
  /**
   * Bean used to validate that a CacheManager exists and provide a more meaningful
   * exception.
   */
  static class CacheManagerValidator {
    @Autowired
    private CacheProperties cacheProperties;
    @Autowired(required = false)
    private CacheManager cacheManager;
    @PostConstruct
    public void checkHasCacheManager() {
      Assert.notNull(this.cacheManager,
          "No cache manager could "
              + "be auto-configured, check your configuration (caching "
              + "type is '" + this.cacheProperties.getType() + "')");
    }
  }
  /**
   * {@link ImportSelector} to add {@link CacheType} configuration classes.
   */
  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;
    }
  }
}

如下所示,添加了11个缓存配置类:

0 = "org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration"
1 = "org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration"
2 = "org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration"
3 = "org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration"
4 = "org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration"
5 = "org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration"
6 = "org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration"
7 = "org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration"
8 = "org.springframework.boot.autoconfigure.cache.GuavaCacheConfiguration"
9 = "org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration"
10 = "org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration"

也就是说,CacheManager产品有:

  • Generic
  • JCache(JSR107)(EhCache3 Hazelcast Infinispan .etc)
  • EhCache 2.X
  • Hazelcast
  • Infinispan
  • Couchbase
  • Redis
  • Caffeine
  • Guava
  • Simple

【2】默认缓存配置

在application.properties中开启debug:debug=true。在控制台即可打印自动配置报告:

默认使用的是SimpleCacheConfiguration!

其源码如下:

@Configuration
@ConditionalOnMissingBean(CacheManager.class)
@Conditional(CacheCondition.class)
class SimpleCacheConfiguration {
  private final CacheProperties cacheProperties;
  private final CacheManagerCustomizers customizerInvoker;
  SimpleCacheConfiguration(CacheProperties cacheProperties,
      CacheManagerCustomizers customizerInvoker) {
    this.cacheProperties = cacheProperties;
    this.customizerInvoker = customizerInvoker;
  }
// 注册了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 (可以获取和创建ConcurrentMapCache)源码如下:

/**
 * {@link CacheManager} implementation that lazily builds {@link ConcurrentMapCache}
 * instances for each {@link #getCache} request. Also supports a 'static' mode where
 * the set of cache names is pre-defined through {@link #setCacheNames}, with no
 * dynamic creation of further cache regions at runtime.
 *
 * <p>Note: This is by no means a sophisticated CacheManager; it comes with no
 * cache configuration options. However, it may be useful for testing or simple
 * caching scenarios. For advanced local caching needs, consider
 * {@link org.springframework.cache.jcache.JCacheCacheManager},
 * {@link org.springframework.cache.ehcache.EhCacheCacheManager},
 * {@link org.springframework.cache.caffeine.CaffeineCacheManager} or
 * {@link org.springframework.cache.guava.GuavaCacheManager}.
 *
 * @author Juergen Hoeller
 * @since 3.1
 * @see ConcurrentMapCache
 */
public class ConcurrentMapCacheManager implements CacheManager, BeanClassLoaderAware {
  private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<String, Cache>(16);
  private boolean dynamic = true;
  private boolean allowNullValues = true;
  private boolean storeByValue = false;
  private SerializationDelegate serialization;
  /**
   * Construct a dynamic ConcurrentMapCacheManager,
   * lazily creating cache instances as they are being requested.
   */
  public ConcurrentMapCacheManager() {
  }
  /**
   * Construct a static ConcurrentMapCacheManager,
   * managing caches for the specified cache names only.
   */
  public ConcurrentMapCacheManager(String... cacheNames) {
    setCacheNames(Arrays.asList(cacheNames));
  }
  /**
   * Specify the set of cache names for this CacheManager's 'static' mode.
   * <p>The number of caches and their names will be fixed after a call to this method,
   * with no creation of further cache regions at runtime.
   * <p>Calling this with a {@code null} collection argument resets the
   * mode to 'dynamic', allowing for further creation of caches again.
   */
  public void setCacheNames(Collection<String> cacheNames) {
    if (cacheNames != null) {
      for (String name : cacheNames) {
        this.cacheMap.put(name, createConcurrentMapCache(name));
      }
      this.dynamic = false;
    }
    else {
      this.dynamic = true;
    }
  }
  /**
   * Specify whether to accept and convert {@code null} values for all caches
   * in this cache manager.
   * <p>Default is "true", despite ConcurrentHashMap itself not supporting {@code null}
   * values. An internal holder object will be used to store user-level {@code null}s.
   * <p>Note: A change of the null-value setting will reset all existing caches,
   * if any, to reconfigure them with the new null-value requirement.
   */
  public void setAllowNullValues(boolean allowNullValues) {
    if (allowNullValues != this.allowNullValues) {
      this.allowNullValues = allowNullValues;
      // Need to recreate all Cache instances with the new null-value configuration...
      recreateCaches();
    }
  }
  /**
   * Return whether this cache manager accepts and converts {@code null} values
   * for all of its caches.
   */
  public boolean isAllowNullValues() {
    return this.allowNullValues;
  }
  /**
   * Specify whether this cache manager stores a copy of each entry ({@code true}
   * or the reference ({@code false} for all of its caches.
   * <p>Default is "false" so that the value itself is stored and no serializable
   * contract is required on cached values.
   * <p>Note: A change of the store-by-value setting will reset all existing caches,
   * if any, to reconfigure them with the new store-by-value requirement.
   * @since 4.3
   */
  public void setStoreByValue(boolean storeByValue) {
    if (storeByValue != this.storeByValue) {
      this.storeByValue = storeByValue;
      // Need to recreate all Cache instances with the new store-by-value configuration...
      recreateCaches();
    }
  }
  /**
   * Return whether this cache manager stores a copy of each entry or
   * a reference for all its caches. If store by value is enabled, any
   * cache entry must be serializable.
   * @since 4.3
   */
  public boolean isStoreByValue() {
    return this.storeByValue;
  }
  @Override
  public void setBeanClassLoader(ClassLoader classLoader) {
    this.serialization = new SerializationDelegate(classLoader);
    // Need to recreate all Cache instances with new ClassLoader in store-by-value mode...
    if (isStoreByValue()) {
      recreateCaches();
    }
  }
  @Override
  public Collection<String> getCacheNames() {
    return Collections.unmodifiableSet(this.cacheMap.keySet());
  }
//根据名字获取Cache组件
  @Override
  public Cache getCache(String name) {
    Cache cache = this.cacheMap.get(name);
    if (cache == null && this.dynamic) {
      synchronized (this.cacheMap) {
        cache = this.cacheMap.get(name);
        if (cache == null) {
          cache = createConcurrentMapCache(name);
          this.cacheMap.put(name, cache);
        }
      }
    }
    return cache;
  }
  private void recreateCaches() {
    for (Map.Entry<String, Cache> entry : this.cacheMap.entrySet()) {
      entry.setValue(createConcurrentMapCache(entry.getKey()));
    }
  }
  /**
   * Create a new ConcurrentMapCache instance for the specified cache name.
   * @param name the name of the cache
   * @return the ConcurrentMapCache (or a decorator thereof)
   */
  protected Cache createConcurrentMapCache(String name) {
    SerializationDelegate actualSerialization = (isStoreByValue() ? this.serialization : null);
    return new ConcurrentMapCache(name, new ConcurrentHashMap<Object, Object>(256),
        isAllowNullValues(), actualSerialization);
  }
}

ConcurrentMapCache作用:将数据保存在ConcurrentMap中,并进行获取。

【3】运行流程

这里以注解@Cacheable为例,过程如下。

① 方法运行之前,先去Cache组件中进行查询。Cache组件是CacheManager根据cacheNames获取,如果没有则自动创建。



② 根据key 从Cache中查询缓存的内容,默认key为使用keyGenerator(默认为SimpleKeyGenerator)生成的。


SimpleKeyGenerator的生成key的策略:

  • 如果没有参数,则key = new SimpleKey();
  • 如果有一个参数,key = 参数值;
  • 如果有多个参数,key = new SimpleKey(params)。

③ 如果没有查到缓存就调用目标方法



④ 将目标方法的返回结果放入缓存中


⑤ 如果从缓存中查到了就不调用目标方法,直接从缓存中获取然后返回

CacheAspectSupport中源码示例如下:

private Cache.ValueWrapper findCachedItem(Collection<CacheOperationContext> contexts) {
    Object result = CacheOperationExpressionEvaluator.NO_RESULT;
    for (CacheOperationContext context : contexts) {
      if (isConditionPassing(context, result)) {
        Object key = generateKey(context, result);
        Cache.ValueWrapper cached = findInCaches(context, key);
        if (cached != null) {
          return cached;
        }
        else {
          if (logger.isTraceEnabled()) {
            logger.trace("No cache entry for key '" + key + "' in cache(s) " + context.getCacheNames());
          }
        }
      }
    }
    return null;
  }


目录
相关文章
|
前端开发 Java 关系型数据库
基于Java+Springboot+Vue开发的鲜花商城管理系统源码+运行
基于Java+Springboot+Vue开发的鲜花商城管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的鲜花商城管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。技术学习共同进步
934 7
|
11月前
|
缓存 负载均衡 监控
135_负载均衡:Redis缓存 - 提高缓存命中率的配置与最佳实践
在现代大型语言模型(LLM)部署架构中,缓存系统扮演着至关重要的角色。随着LLM应用规模的不断扩大和用户需求的持续增长,如何构建高效、可靠的缓存架构成为系统性能优化的核心挑战。Redis作为业界领先的内存数据库,因其高性能、丰富的数据结构和灵活的配置选项,已成为LLM部署中首选的缓存解决方案。
1005 25
|
11月前
|
缓存 并行计算 监控
vLLM 性能优化实战:批处理、量化与缓存配置方案
本文深入解析vLLM高性能部署实践,揭秘如何通过continuous batching、PagedAttention与前缀缓存提升吞吐;详解批处理、量化、并发参数调优,助力实现高TPS与低延迟平衡,真正发挥vLLM生产级潜力。
2696 0
vLLM 性能优化实战:批处理、量化与缓存配置方案
|
11月前
|
XML JSON Java
【SpringBoot(三)】从请求到响应再到视图解析与模板引擎,本文带你领悟SpringBoot请求接收全流程!
Springboot专栏第三章,从请求的接收到视图解析,再到thymeleaf模板引擎的使用! 本文带你领悟SpringBoot请求接收到渲染的使用全流程!
704 3
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
1953 5
|
存储 缓存 Java
Spring中@Cacheable、@CacheEvict以及其他缓存相关注解的实用介绍
缓存是提升应用性能的重要技术,Spring框架提供了丰富的缓存注解,如`@Cacheable`、`@CacheEvict`等,帮助开发者简化缓存管理。本文介绍了如何在Spring中配置缓存管理器,使用缓存注解优化数据访问,并探讨了缓存的最佳实践,以提升系统响应速度与可扩展性。
497 0
Spring中@Cacheable、@CacheEvict以及其他缓存相关注解的实用介绍
|
XML Java 应用服务中间件
SpringBoot项目打war包流程
本文介绍了将Spring Boot项目改造为WAR包并部署到外部Tomcat服务器的步骤。主要内容包括:1) 修改pom.xml中的打包方式为WAR;2) 排除Spring Boot内置的Tomcat依赖;3) 添加Servlet API依赖;4) 改造启动类以支持WAR部署;5) 打包和部署。通过这些步骤,可以轻松地将Spring Boot应用转换为适合外部Tomcat服务器的WAR包。
967 64
SpringBoot项目打war包流程
|
消息中间件 缓存 NoSQL
基于Spring Data Redis与RabbitMQ实现字符串缓存和计数功能(数据同步)
总的来说,借助Spring Data Redis和RabbitMQ,我们可以轻松实现字符串缓存和计数的功能。而关键的部分不过是一些"厨房的套路",一旦你掌握了这些套路,那么你就像厨师一样可以准备出一道道饕餮美食了。通过这种方式促进数据处理效率无疑将大大提高我们的生产力。
437 32
|
缓存 NoSQL 数据库
Django缓存机制详解:从配置到实战应用
本文全面解析Django缓存技术,涵盖配置方法与六大缓存后端,结合实战场景演示四种典型应用方式,帮助开发者提升Web应用性能,应对高并发挑战。
445 0
|
缓存 NoSQL API
Django缓存机制详解:从配置到实战应用
本文介绍了 Django 缓存机制的基础知识与实战应用,涵盖缓存概念、Redis 安装配置、缓存策略及 API 使用,并通过 RBAC 权限系统演示缓存的读写与删除操作,助力提升 Web 应用性能。
388 0