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

PRA*_*P S 6 caching spring-boot spring-cache

我在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);
    }
Run Code Online (Sandbox Code Playgroud)

这绝对是正常的.

但是要实现缓存,应该定义一个必需的CacheManager/Cacheprovider.没有定义任何cacheManager也我的应用程序工作正常.

是否有Spring定义的默认缓存管理器?Spring文档说Spring Boot自动配置一个合适的CacheManager.

那么如果我们不定义CacheManager会使用什么呢?

Dan*_*ski 7

Spring Boot启动器提供了一个简单的缓存提供程序,该提供程序将值存储在ConcurrentHashMap的实例中。这是缓存机制的最简单的线程安全实现。

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

  • 正确。ConcurrentHashMap是默认使用的,对于简单的用例来说可能就足够了。但是,如果需要对缓存进行更多控制,例如最大缓存容量或特定存储的生存时间,则应考虑其他提供商。咖啡因很可能是所有可能性中最简单的提供者。 (2认同)
  • 2022:Spring Boot 缓存文档现在位于:https://docs.spring.io/spring-boot/docs/current/reference/html/io.html#io.caching (2认同)

小智 6

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

@Bean
public CacheManager cacheManager() {
    return new org.springframework.cache.concurrent.ConcurrentMapCacheManager();
}
Run Code Online (Sandbox Code Playgroud)