【问题标题】:How to remove the entire cache, and then pre-populate the cache?如何删除整个缓存,然后预填充缓存?
【发布时间】:2018-05-06 12:31:27
【问题描述】:

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

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>

【问题讨论】:

    标签: spring-boot spring-cache ehcache-3


    【解决方案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();
    }  
    

    【讨论】:

      猜你喜欢
      • 2021-10-26
      • 1970-01-01
      • 2016-11-07
      • 2013-01-27
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多