首页 > 解决方案 > Java应用程序中的Spring缓存实现?

问题描述

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

@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 Boot 实现并使用不同的注释示例。我想我应该从3.1开始。在使用 Spring Boot 时使用 Spring Boot部分,但我不确定应该使用哪个缓存注释(4.1。@Cacheable 似乎没问题,但我不确定)。

那么,我应该在哪里放置SimpleCacheCustomizer以及如何将这种方法应用于上面的服务方法(findAllByCountry)?任何简单的例子都会非常感激,因为我是 Spring 的新手。

标签: javaspringspring-bootcaching

解决方案


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

@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
}

准备好了,这是基本设置


推荐阅读