【问题标题】:Spring @cache not working for caching list with no parmsSpring @cache 不适用于没有参数的缓存列表
【发布时间】:2014-09-12 22:32:52
【问题描述】:

您好,我在尝试缓存列表函数的结果时遇到问题 当我第一次调试它时,第二次调用该函数时,缓存什么也不返回一个空列表 我还尝试添加 key="'all'" 和方法名称,但什么也没回来

@Override
@Cacheable(value = "categories" )
public List<Category> getCategories() {
    // TODO Auto-generated method stub
    LOG.info("start getCategories");
    return repository.findAll(); //
}
@Configuration
@EnableCaching
public class CachingConfig implements CachingConfigurer {
@Bean(destroyMethod="shutdown")
public net.sf.ehcache.CacheManager ehCacheManager() {
     net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();



    CacheConfiguration cacheConfigurationCategories = new CacheConfiguration();
    cacheConfigurationCategories.setName("categories");

    cacheConfigurationCategories.setMemoryStoreEvictionPolicy("LRU");
    cacheConfigurationCategories.setMaxEntriesLocalHeap(100);
    cacheConfigurationCategories.setMaxElementsOnDisk(100);
    config.addCache(cacheConfigurationCategories);

    return net.sf.ehcache.CacheManager.newInstance(config);
}

@Bean
@Override
public CacheManager cacheManager() {
    return new EhCacheCacheManager(ehCacheManager());
}

@Bean
@Override
public KeyGenerator keyGenerator() {
    return new SimpleKeyGenerator();
}

}

【问题讨论】:

  • 代码看起来没问题,因此 repository.findAll 没有返回任何内容,或者您​​的缓存配置错误。
  • 嗨添加了我的缓存配置

标签: java spring caching


【解决方案1】:

我只将它与xml中的配置一起使用,看起来像这样

    @Bean(name = "ehcache")
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
        EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
        ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        return ehCacheManagerFactoryBean;
    }

    @Bean
    public CacheManager cacheManager() {
        EhCacheCacheManager cacheManager = new EhCacheCacheManager();
        cacheManager.setCacheManager(ehCacheManagerFactoryBean().getObject());
        return cacheManager;
    }

使用以下xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
    <diskStore path="java.io.tmpdir"/>

<cache name="cacheName"
       maxElementsInMemory="1000"
       eternal="false"
       timeToIdleSeconds="28800"
       timeToLiveSeconds="28800"
       overflowToDisk="false"
       maxElementsOnDisk="200"
       diskPersistent="false"
       diskExpiryThreadIntervalSeconds="120"
       memoryStoreEvictionPolicy="LRU"/>             

</ehcache>

【讨论】:

  • 你能放你的xml吗?
  • 很难说可能出了什么问题。尝试在可缓存的注解中添加一个键。
  • 它适用于单个元素,但不适用于对象列表,我尝试了 key 但没有运气
  • 不知道还能做什么。打开日志记录并尝试最简单的情况。
猜你喜欢
  • 2021-01-25
  • 2018-10-26
  • 2017-03-29
  • 1970-01-01
  • 2015-08-07
  • 2016-08-26
  • 1970-01-01
  • 1970-01-01
  • 2018-05-27
相关资源
最近更新 更多