0

有人可以告诉我下面的实现有什么问题。我正在尝试删除整个缓存,其次,我想预填充/填充缓存。但是,当执行这两种方法时,我在下面仅删除两个缓存,而不是预填充/启动缓存。任何想法?

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;

@Cacheable(cacheNames = "cacheOne")
List<User> cacheOne() throws Exception {...}

@Cacheable(cacheNames = "cacheOne")
List<Book> cacheTwo() throws Exception {...}

@Caching (
        evict = {
                @CacheEvict(cacheNames = "cacheOne", allEntries = true),
                @CacheEvict(cacheNames = "CacheTwo", allEntries = true)
        }
)
void clearAndReloadEntireCache() throws Exception
{
    // Trying to reload cacheOne and cacheTwo inside this method
    // Is this even possible? if not what is the correct approach?
    cacheOne();
    cacheTwo(); 
}

我有 spring boot 应用程序(v1.4.0),更重要的是,利用以下依赖项:

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
     <groupId>org.ehcache</groupId>
     <artifactId>ehcache</artifactId>
     <version>3.3.0</version>
 </dependency>
 <dependency>
     <groupId>javax.cache</groupId>
     <artifactId>cache-api</artifactId>
     <version>1.0.0</version>
 </dependency>
4

1 回答 1

1

如果调用该clearAndReloadEntireCache()方法,缓存拦截器只会处理该方法。调用同一对象的其他方法:cacheOne()并且cacheTwo()不会在运行时导致缓存拦截,尽管它们都用@Cacheable.

您可以通过使用如下所示的两个方法调用重新加载cacheOnecacheTwo来实现所需的功能:

@Caching(evict = {@CacheEvict(cacheNames = "cacheOne", allEntries = true, beforeInvocation = true)},
        cacheable = {@Cacheable(cacheNames = "cacheOne")})
public List<User> cleanAndReloadCacheOne() {
    return cacheOne();
}

@Caching(evict = {@CacheEvict(cacheNames = "cacheTwo", allEntries = true, beforeInvocation = true)},
        cacheable = {@Cacheable(cacheNames = "cacheTwo")})
public List<Book> cleanAndReloadCacheTwo() {
    return cacheTwo();
}  
于 2017-11-25T19:51:21.703 回答