使用spring缓存的java缓存属性
我正在尝试使用spring cache对我的方法实现缓存。问题是,在第一次之后,这个方法没有被执行,这意味着属性没有被加载。如果我删除@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>
# 1 楼答案
代码工作正常:按照您配置} 参数并向其传递SPeL表达式,但仍然无法检查基础文件是否已更改并有条件地执行方法体
Cacheable
注释的方式,它实际上永远不会失效,因为不存在触发逐出的条件。通常,您可以使用^{“缓存直到更改”的这种实现无法工作,因为在实际重新加载文件(或检查其大小或时间戳,无论什么)之前,您都不知道是否添加了新属性
如果定期重新加载是一种可接受的选择,那么可以尝试Apache Commons配置“ReloadingFileBasedConfigurationBuilder或使用Spring的^{} 进行实验