[英]Caching properties using spring Cache
我正在嘗試使用Spring緩存對我的方法實現緩存。 問題在於,第一次不執行此方法后,這意味着未加載屬性。 如果我刪除@Cacheable批注,它將正常工作。 我的要求是,僅當添加新屬性時,此方法才應運行並加載屬性,否則應從緩存中返回。
@Cacheable("mycache")
public Properties loadPropertyFile() throws Throwable {
Properties properties = new Properties();
try {
logger.debug("Loading properties.");
if (this.locations != null) {
for (Resource location : this.locations) {
if (logger.isInfoEnabled()) {
logger.info("Loading properties file from " + location);
}
try {
properties = PropertiesLoaderUtils.loadAllProperties(location.getFilename());
} catch (IOException ex) {
if (this.ignoreResourceNotFound) {
if (logger.isWarnEnabled()) {
logger.warn("Could not load properties from "
+ location + ": " + ex.getMessage());
}
} else {
throw ex;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return properties;
}
XML檔案:
<cache:annotation-driven />
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="mycache" />
</set>
</property>
該代碼正常工作:由於沒有條件觸發逐出,因此您配置Cacheable
批注的方式實際上永遠不會失效。 通常,您可以使用condition
參數並將SPeL表達式傳遞給它,但是仍然無法檢查基礎文件是否已更改並有條件地執行方法主體。
這種“直到更改之前緩存”的實現無法正常工作,因為在實際重新加載文件(或檢查其大小或時間戳等之后)之前,您不知道是否添加了“新屬性” 。
如果可以選擇定期進行重新加載,則可以嘗試使用Apache Commons Configurations的ReloadingFileBasedConfigurationBuilder或嘗試使用Spring的@Scheduled
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.