您好,我在执行方法时遇到清理缓存的问题。 这是我的配置和缓存方法:
@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://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/