java - Spring Cache Evict 不起作用

标签 java spring caching

您好,我在执行方法时遇到清理缓存的问题。 这是我的配置和缓存方法:

@Configuration
@EnableCaching
@AutoConfigureAfter(value = {MetricsConfiguration.class, DatabaseConfiguration.class})
@Profile("!" + Constants.SPRING_PROFILE_FAST)
public class CacheConfiguration {

    private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
    public static final String STOCK_DETAILS_BY_TICKER_CACHE = "stockDetailsByTickerCache";
    public static final String RSS_NEWS_BY_TYPE_CACHE = "rssNewsByTypeCache";

    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        List<Cache> caches = new ArrayList<Cache>();
        caches.add(new ConcurrentMapCache(STOCK_DETAILS_BY_TICKER_CACHE));
        caches.add(new ConcurrentMapCache(RSS_NEWS_BY_TYPE_CACHE));
        cacheManager.setCaches(caches);
        return cacheManager;
    }
}

我要缓存的这个方法:

@Cacheable(cacheNames = CacheConfiguration.RSS_NEWS_BY_TYPE_CACHE, key = "#type")
    public ResponseEntity<List<NewsDetailsDTO>> getLatestNewsMessageByType(RssType type) {
        Pageable pageable = new PageRequest(0, 5, Sort.Direction.DESC, "createdDate");
        List<NewsMessage> latestNewsMessage = newsMessageRepository.findByType(type, pageable).getContent();
        return new ResponseEntity<List<NewsDetailsDTO>>(mapToDTO(latestNewsMessage), HttpStatus.OK);
    }

执行此方法时,我想按类型清理缓存:

@CacheEvict(cacheNames={CacheConfiguration.RSS_NEWS_BY_TYPE_CACHE}, beforeInvocation = true, key = "#news.type")
    public void save(NewsMessage news) {
        newsMessageRepository.save(news);
    }

NewsMessage 对象看起来像:

@Entity
@Table(name = "NEWS_MESSAGE")
public class NewsMessage extends ChatMessage {

    <other fileds>

    @NotNull
    @Enumerated(EnumType.STRING)
    private RssType type;
}

缓存工作正常,第一次查询数据库,然后从缓存中获取数据。问题是当我更新数据时,@CacheEvict 不会清理缓存。我试图使用此注释清除所有缓存: @CacheEvict(cacheNames={CacheConfiguration.RSS_NEWS_BY_TYPE_CACHE}, allEntries = true) 但它也不起作用。你能帮帮我吗?

最佳答案

从哪里调用save() 方法?

在您自己的回答中,您似乎已将注释移动到另一个类/接口(interface)以调用该类/接口(interface)的代理对象(顺便说一句,通常不应在接口(interface)中使用注释,因为它们通常不会被捕获默认配置)。

因此我的问题是:你知道 spring aop 代理吗?您必须从 MessageRepository 类外部的方法调用带注释的方法才能调用代理对象。

一般文档在这里:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#aop-understanding-aop-proxies

或这里有例子http://spring.io/blog/2012/05/23/transactions-caching-and-aop-understanding-proxy-usage-in-spring

关于java - Spring Cache Evict 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37009859/

相关文章:

java - JRuby:更改了 CLASSPATH 但没有效果

java - 如何使用 Java 流迭代一个大列表以使其更小以供 REST 调用?

caching - 用于 Redis 缓存和 TTL 的 ASP.NET session 状态提供程序

java - 如何在 Spring 中返回字段的不同值

ruby-on-rails-3 - 如何在rails中使用多个缓存? (真的)

caching - 在 Angular2 中使用 RxJs 5 为 REST 客户端提供基于时间的缓存

java - thymeleaf :each repair

java - 为什么 exception.getCause() == 异常?

spring - Java应用程序构建失败,其中Mysql url指向Docker容器

java - 方法签名内的@Validation