Spring Java 应用中的缓存实现?

Spring Caching Implementation in a Java app?

在我的 Java 基于 Spring Boot 的应用程序中,我正在尝试为以下服务方法实现缓存机制:

@Override
public List<EmployeeDTO> findAllByCountry(Country country) {
    final Map<Pair<UUID, String>, List<CountryTranslatable>> valueList 
        = countryRepository...
        // code omitted for brevity
}

关于这个问题的几个例子之后,我决定采用 A Guide To Caching in Spring 中提到的方法。

但是,我有点困惑,因为它包含 Spring 和 Spring 引导实现并使用不同的注释示例。我想我应该从3.1开始。使用 Spring Boot 部分,因为我使用 Spring Boot,但我不确定我应该使用哪个缓存注释(4.1。@Cacheable 似乎没问题,但我不确定) .

那么,我应该把 SimpleCacheCustomizer 放在哪里,以及如何将这种方法应用于我上面的服务方法 (findAllByCountry)?任何简单的例子都将不胜感激,因为我是 Spring.

的新手

您应该将您的 SimpleCacheCustomizer 与其他 Spring 配置放在一起 class。这样,您的组件将被 Spring.

扫描和加载
@Component
public class SimpleCacheCustomizer 
  implements CacheManagerCustomizer<ConcurrentMapCacheManager> {

    @Override
    public void customize(ConcurrentMapCacheManager cacheManager) {
        cacheManager.setCacheNames(asList("employeesList", "otherCacheName"));
    }
}

要在您的服务中使用缓存,请添加注释 @Cacheable("employeesList")

@Cacheable("employeesList")
@Override
public List<EmployeeDTO> findAllByCountry(Country country) {
    final Map<Pair<UUID, String>, List<CountryTranslatable>> valueList 
        = countryRepository...
        // code omitted for brevity
}

如果您想验证缓存是否正常工作,只需在您的 Spring 配置中启用 sql_query 并检查 findAllByCountry 是否不再向数据库发出任何请求。

如果您想自定义自动配置的缓存管理器,那么您只需要实现 CacheManagerCustomizer 接口。

通常情况下您不需要自定义自动配置的缓存管理器。该示例已在您所附的 link 中给出。

您对可缓存注释的理解也是正确的,它应该适合您。

您可以将该组件 class 与其他 class 放在组件扫描范围内。

如果您是初学者,则不需要任何定制,您只需要基础知识,然后执行以下操作

@Configuration
@EnableCaching
public class CachingConfig {

    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager();
    }
}

提供的文章指出,return new ConcurrentMapCacheManager("addresses"); 但您可以使用默认构造函数,稍后将使用 @Cacheable("addresses") 创建地址的相关缓存。所以不需要这个在配置中。

你还需要

@Cacheable("employeesList")
@Override
public List<EmployeeDTO> findAllByCountry(Country country) {
    final Map<Pair<UUID, String>, List<CountryTranslatable>> valueList 
        = countryRepository...
        // code omitted for brevity
}

准备就绪,这是基本设置