【问题标题】:How should I use @Cacheable on spring data repositories我应该如何在 Spring 数据存储库上使用 @Cacheable
【发布时间】:2015-09-06 23:29:24
【问题描述】:

例如,当使用MongoRepository 时,我想将一些方法标记为@Cacheable,例如insert(entity)findOne(id)。 由于它是 Spring 存储库而不是我的,我应该如何在这些方法上使用 @Cacheable

【问题讨论】:

  • 你缓存的目的是什么?你想减少数据库读取访问还是什么?
  • 通常这是缓存的主要目的,是的。
  • 所以,您遵循了我假设的文档。什么不起作用?
  • 我会详细说明:spring MongoRepository 扩展了其他 spring 存储库接口。其中一个接口包括方法 getOne(String id) 。我需要在spring接口中添加@Cacheable吗?我怀疑。由于我按原样使用 MongoRepository,我应该将缓存注释放在哪里?
  • 将注解添加到您的服务层、调用 Spring Data 存储库的方法中。

标签: java spring-boot spring-data


【解决方案1】:

不确定您实际上是如何使用MongoRepository,您似乎是在建议您直接使用它(在问题中包含您的代码通常是个好主意),但是参考文档解释了使用此接口的基础知识(事实上,Spring Data 中的所有存储库接口):"§ 6.1. Core concepts":

(...) 此接口主要用作标记接口,以捕获要使用的类型并帮助您发现扩展此接口的接口。 (...)

您的自定义存储库将类似于:

public interface SomeTypeMongoRepository extends MongoRepository<SomeType, Long> {
    @Override
    @CacheEvict("someCache")
    <S extends SomeType> S insert(S entity);

    @Override
    @Cacheable("someCache")
    SomeType findOne(Long id);
}

(请注意,它基于我的一个 cmets 中包含的 official example

【讨论】:

    【解决方案2】:

    docs 中所述,其中一个选项可能是在 xml 中执行。

    这种方法的另一个好处是您可以通过一个声明使多个方法可缓存。

    【讨论】:

    • 它与添加服务层并在其方法上声明缓存注释的方法相同。我想逃离服务层,因为我不需要。
    猜你喜欢
    • 2010-12-14
    • 2012-11-12
    • 2012-06-20
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 2017-05-01
    • 2012-12-17
    • 2011-04-23
    相关资源
    最近更新 更多