使用@EnableCaching的Spring引导的默认缓存管理器

使用@EnableCaching的Spring引导的默认缓存管理器,caching,spring-boot,spring-cache,Caching,Spring Boot,Spring Cache,我已经在SpringBootApplication中实现了缓存,如下所示 @SpringBootApplication @EnableCaching public class SampleApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {

我已经在SpringBootApplication中实现了缓存,如下所示

@SpringBootApplication
@EnableCaching
public class SampleApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SampleApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(SampleApplication.class, args);
    }
这绝对有效

但要实现缓存,必须定义一个强制的CacheManager/Cacheprovider。 没有定义任何cacheManager,我的应用程序也运行良好

是否有Spring定义的默认缓存管理器? SpringDocs说SpringBoot自动配置了一个合适的CacheManager


那么,如果我们不定义CacheManager,它将使用什么呢?

Spring Boot starter提供了将值存储在的实例中的功能。这是缓存机制最简单的线程安全实现


如果应用程序中存在
@EnableCaching
注释,Spring Boot将检查类路径上可用的依赖项,并配置适当的
CacheManager
。根据选择的提供商,可能需要一些额外的配置。您可以在此答案的第一个链接中找到有关配置的所有信息。

如果您想明确(出于任何原因)定义最简单的缓存管理器(在引擎盖下使用ConcurrentHashMap),请执行以下操作:

@Bean
public CacheManager cacheManager() {
    return new org.springframework.cache.concurrent.ConcurrentMapCacheManager();
}

谢谢,如果应用程序中未定义任何内容,那么ConcurrentHashMap本身将作为默认缓存提供程序。这会影响ConcurrentHashMap作为提供程序的应用程序的性能吗?正确。默认情况下使用ConcurrentHashMap,对于简单的用例可能就足够了。但是,如果需要对缓存进行更多控制(例如,特定存储的最大缓存容量或生存时间),则应查看其他提供程序。咖啡因很可能是所有可能性中最简单的提供者。