【问题标题】:What order are cache layers when using spring @Caching?使用spring @Caching时缓存层的顺序是什么?
【发布时间】:2017-04-12 20:18:45
【问题描述】:

使用@Caching注解,spring允许在一个方法中添加多个@Cacheable注解。由于conditional caching 可以使用@Cacheable,因此注释以及评估条件的顺序是什么 - 如果多个缓存评估为真,值是否存储在多个缓存中?再次在缓存获取期间,是否并行评估所有条件,并从条件评估为真的任何缓存中获取值?

例如考虑:

@Caching( cacheable = { @Cacheable(cacheNames="smallBooks", condition="#name.length < 32"), @Cacheable(cacheNames="fiction", condition="#domain.equals('fiction')"), @Cacheable(cacheNames="everythingelse")})
public Book findBook(String name, String domain)

【问题讨论】:

    标签: java spring caching spring-cache


    【解决方案1】:

    不,没有并行评估,@Cacheable 注释根据链接代码得到gathered in the order of definition(可缓存属性毕竟是一个数组)。重要的是要意识到您正在以不同的名称和条件定义 3 个单独的缓存。

    由于我不知道您的用例,这里是对 Spring Caching Guide 的轻微改动:

    //..
    @Override
    @Caching( cacheable = {
            @Cacheable(cacheNames = "sth"),
            @Cacheable(cacheNames="everythingelse")
    })
    public Book getByIsbn(String isbn) {
        simulateSlowService();
        return new Book(isbn, "Some book");
    }
    //..
    

    并通过在 Spring Boot 的 application.properties 中的缓存包中定义 DEBUG 级别:

    logging.level.org.springframework.cache=DEBUG
    

    您可以看到它实际上是如何作为单独的缓存加载的:

    2016-11-29 00:52:26.472 DEBUG 23426 --- [           main] o.s.c.a.AnnotationCacheOperationSource   : Adding cacheable method 'getByIsbn' with attribute: [Builder[public hello.Book hello.SimpleBookRepository.getByIsbn(java.lang.String)] caches=[sth] | key='' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='' | unless='' | sync='false', Builder[public hello.Book hello.SimpleBookRepository.getByIsbn(java.lang.String)] caches=[everythingelse] | key='' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='' | unless='' | sync='false']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-23
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      相关资源
      最近更新 更多