使用 spring @Caching 时缓存层的顺序是什么?

What order are cache layers when using spring @Caching?

使用@Cacheable 可以使用@Caching annotation, spring allows adding multiple @Cacheable annotations to a single method. Since conditional caching,注释的顺序是什么,因此评估的条件是什么-如果多个缓存的计算结果为真,值是否存储在多个缓存中?再次在缓存获取期间,所有条件是否并行评估,并从条件评估为真的任何缓存中获取值?

例如考虑:

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

不,没有并行评估,@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 引导 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']