Spring @Cacheable并不起作用

时间:2016-10-01 01:06:02

标签: spring ehcache spring-cache

我有下一个方法的服务:

public Optional<Test> getTestWithId100() {
    return get(100);
}

@Cacheable(value = "test", key = "'1'")
public Optional<Test> get(long id) {
    log.error("not from cache");
    return testRepository.findOneById(id);
}

我从控制器调用方法getTestWithId100,但它只获得新值。

@Slf4j
@Configuration
@EnableCaching
@AutoConfigureAfter(value = { MetricsConfiguration.class, DatabaseConfiguration.class })
public class CacheConfiguration {

    @PersistenceContext
    private EntityManager entityManager;

    private final MetricRegistry metricRegistry;

    private net.sf.ehcache.CacheManager cacheManager;

    @Inject
    public CacheConfiguration(MetricRegistry metricRegistry) {
        this.metricRegistry = metricRegistry;
    }

    @PreDestroy
    public void destroy() {
        log.info("Remove Cache Manager metrics");
        SortedSet<String> names = metricRegistry.getNames();
        names.forEach(metricRegistry::remove);
        log.info("Closing Cache Manager");
        cacheManager.shutdown();
    }

    @Bean
    public CacheManager cacheManager(Properties properties) {
        log.debug("Starting Ehcache");
        cacheManager = net.sf.ehcache.CacheManager.create();
        cacheManager.getConfiguration().setMaxBytesLocalHeap(properties.getCache().getEhcache().getMaxBytesLocalHeap());
        log.debug("Registering Ehcache Metrics gauges");
        entityManager.getMetamodel().getEntities().forEach(entity -> {
            String name = entity.getName();
            if (name == null || entity.getJavaType() != null)
                name = entity.getJavaType().getName();
            Assert.notNull(name, "entity cannot exist without a identifier");
            net.sf.ehcache.Cache cache = cacheManager.getCache(name);
            if (cache != null)
                cacheManager.replaceCacheWithDecoratedCache(cache, InstrumentedEhcache.instrument(metricRegistry, cache));
        });
        EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
        ehCacheManager.setCacheManager(cacheManager);
        return ehCacheManager;
    }

}

ehcache.xml的一部分:

<cache name="test" eternal="true"/>

为什么它不起作用?我尝试了不同的键但没有成功。

2 个答案:

答案 0 :(得分:2)

Spring注释通过代理/增强您的类来工作。此系统中的一个限制是当您在同一个bean上调用方法时,系统不会拦截该调用,因此不会应用基于注释的修改。

答案 1 :(得分:0)

我认为你cache config错了,让我们考虑下面的代码(对我来说很合适):<​​/ p>

@Bean
public CacheManager cacheManager() {
    return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}

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

当然,ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd"
    updateCheck="true"
    monitoring="autodetect"
    dynamicConfig="true">

    <diskStore path="java.io.tmpdir" />

    <cache name="movieFindCache"
        maxEntriesLocalHeap="10000"
        maxEntriesLocalDisk="1000"
        eternal="false"
        diskSpoolBufferSizeMB="20"
        timeToIdleSeconds="300" timeToLiveSeconds="600"
        memoryStoreEvictionPolicy="LFU"
        transactionalMode="off">
        <persistence strategy="localTempSwap" />
    </cache>

</ehcache>

此配置必须帮助您,如果它没有解决问题,请通知我。 HTH