当前位置: 首页 > 知识库问答 >
问题:

Spring@Cacheable不起作用

庄飞
2023-03-14

我有一个服务与下一个方法:

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个答案

壤驷乐邦
2023-03-14

我认为你在缓存配置中是错误的,让我们考虑下面的代码(它对我来说很好):

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

此配置必须帮助您,如果无法解决问题,请通知我。嗯

严瑞
2023-03-14

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

 类似资料:
  • 我使用@cacheable缓存spring 3.2中服务层的方法的结果。服务类内部使用以下方法代码: xml配置 由于使用JDK1.6,无法使用EhCache。通过使用上面的代码模式,我无法缓存列表结果。当我调用上面的方法时,总是调用DAO。告诉我代码有什么问题。 提前道谢。

  • 问题内容: 一个在方法-annotated类不被异步调用-它阻塞线程。 我已经进入配置,对方法的调用来自类外部,因此应该点击代理。当我单步执行代码时,确实会碰到代理,但似乎没有在与在任务执行器中运行相关的任何类附近的任何地方。 我已经设置了断点,但是它们从未被击中。我已经调试过,可以看到建议得到应用。 该服务被定义为接口(该接口的方法带有适当的注释),实现的方法也带有注释。都没有标记。 任何想法可

  • 问题内容: 呈现视图时,我遇到了hibernate和延迟加载的(著名的)问题....很多人说,仅有的两种解决方案是: 使方法具有事务性(这并不总是可取的) 使用OpenSessionInViewInterceptor。 后者是可取的IMO。无论如何,我不确定此拦截器是否正在触发(实际上,我得到了相同的延迟加载异常,并且没有任何变化): 我使用的是基于简单注释的URL映射,因此请阅读Spring 3

  • 我使用Spring AOP来实现我的应用程序的日志系统。但我有一些麻烦。 我有简单的课

  • 当我从not bean类中的方法调用Cacheable方法时,我突然发现@Cacheable不起作用。 请在下面找到我的代码,并帮助我什么是问题或我错过的东西。

  • 问题内容: 从同一bean的另一个方法调用缓存的方法时,Spring缓存不起作用。 这是一个示例,可以清楚地说明我的问题。 组态: 缓存的服务: 结果: 该方法调用使用缓存在第二次调用预期。但是,在类中()中调用该方法时,则未使用Cache。 这是Spring缓存的工作方式还是我缺少什么? 问题答案: 我相信这是这样的。从我记得阅读的内容来看,生成了一个代理类,该代理类可以拦截所有请求并使用缓存的