【问题标题】:Unable to use Spring @Cacheable and @EnableCaching无法使用 Spring @Cacheable 和 @EnableCaching
【发布时间】:2015-11-26 06:57:31
【问题描述】:

我正在尝试替换旧的:

@Component
public interface MyEntityRepository extends JpaRepository<MyEntity, Integer> {

    @QueryHints({@QueryHint(name = CACHEABLE, value = "true")})
    MyEntity findByName(String name);
}

通过这个:

@Component
public interface MyEntityRepository extends JpaRepository<MyEntity, Integer> {

    @Cacheable(value = "entities")
    MyEntity findByName(String name);
}

因为我想使用高级缓存功能,例如不缓存空值等。

为此,我遵循了 Spring 教程https://spring.io/guides/gs/caching/

如果我不注释我的 Application.java,缓存根本不起作用。

但如果我添加 @EnableCaching 和一个 CacheManager bean:

package my.application.config;

@EnableWebMvc
@ComponentScan(basePackages = {"my.application"})
@Configuration
@EnableCaching
public class Application extends WebMvcConfigurerAdapter {

    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("entities");
    }

// ...
}

我在启动时收到以下错误:

java.lang.IllegalStateException:未指定 CacheResolver,也未找到 CacheManager 类型的 bean。注册一个 CacheManager bean 或者从你的配置中移除 @EnableCaching 注解

如果我用 CacheResolver bean 替换 My CacheManager bean,我会得到同样的错误:

@Bean
public CacheResolver cacheResolver() {
    return new SimpleCacheResolver(new ConcurrentMapCacheManager("entities"));
}

我错过了什么吗?

【问题讨论】:

  • 实现CacheConfigurer接口。并实施方法。需要该类型的 bean 才能正确配置缓存。
  • 尝试使用您在 @cacheable 注释中使用的名称 (entities ) 命名您的 cacheManager。
  • @M. Deinum 昨天这个CacheConfigurer 接口是什么?没有文档。
  • 是的。检查提示/提示here
  • 您是真的在遵循该教程还是在“遵循”该教程。您有一个教程没有的 Web 应用程序。本教程假设您不是 Spring Boot……所以这些是完全不同的事情。

标签: java spring caching spring-data


【解决方案1】:

@herau 你说得对,我必须为 bean 命名! 问题是还有另一个bean“cacheManager”,所以最后我没有注释Application,并创建了一个配置为:

@EnableCaching
@Configuration
public class CacheConf{
    @Bean(name = "springCM")
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("entities");
    }
}

MyEntityRepository:

    @Cacheable(value = "entities", cacheManager = "springCM")
    MyEntity findByName(String name);

【讨论】:

    【解决方案2】:

    在我的例子中,Spring Boot 库很旧,没有办法轻松升级它。所以我使用了 EHCache 2 版本,它在我的应用程序中工作。这是一个我觉得有用的项目可以参考:https://github.com/TechPrimers/spring-ehcache-example/blob/master/src/main/resources/ehcache.xml

    【讨论】:

      猜你喜欢
      • 2017-05-22
      • 2018-03-30
      • 2018-02-02
      • 2019-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      相关资源
      最近更新 更多