【问题标题】:Spring @Cacheable not working properly with custom key in springSpring @Cacheable 在 Spring 中无法与自定义键一起正常工作
【发布时间】:2023-04-07 15:25:01
【问题描述】:

对于 cachedData 的不同值,它每次都从参数中的 cachedData 获取响应日期,而根据我的理解,如果对于特定的 propertyId,如果有一些带有一些 cachedData 参数的调用,它不应该再次获取,而是应该从缓存。

我的方法

@Cacheable(value = "responseCached", key="#propertyId", condition = "#result != null")
public Date fetchCachedData(String propertyId, Map<String, Date> cachedData) {
    return cachedData.get(propertyId);
}

ehCacheConfig

@EnableCaching
@Configuration
public class EhCacheConfig {

    @Bean
    public EhCacheManagerFactoryBean ehCacheManagerFactory(){
        EhCacheManagerFactoryBean ehCacheBean = new EhCacheManagerFactoryBean();
        ehCacheBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        ehCacheBean.setShared(true);
        return ehCacheBean;
    }

    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        List<Cache> caches = new ArrayList<Cache>();
        caches.add(new ConcurrentMapCache("responseCached"));
        cacheManager.setCaches(caches);
        return cacheManager;
    }
}

【问题讨论】:

    标签: java spring-boot caching ehcache spring-cache


    【解决方案1】:

    我认为您对一般概念有误解。如果您使用@Cacheable 注释方法,则避免执行此方法,以防数据已经在缓存中。在您的示例中,缓存是ConcurrentMapCache 而不是cachedData。简单的例子是:

    @Cacheable(value = "responseCached", key="#propertyId")
    public Date fetchData(String propertyId) {
        // computing or I/O intensive code to produce result here
        Date d = ...
        return d;
    }
    

    对于唯一的propertyId,方法fetchData 只执行一次。您可以省略键定义,因为它是唯一的参数。

    注意您的方法名称fetchCachedData:Spring 缓存抽象的想法是,该方法的用户(理想情况下)不需要知道某些内容是否被缓存。最好以业务领域中的某些内容命名您的方法,例如 fetchOfferDate

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 2015-03-24
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      相关资源
      最近更新 更多