http://www.cnblogs.com/nexiyi/p/java_memory_model_and_thread.html
我们在开发Java程序的时候,很多常量信息都存在配置文件中,比如数据库连接信息、ip黑名单,事件的超时时间等等。当需要该这些配置的值时都需要重新启动进程,改动的配置才会生效,有时候线上的应用不能容忍这种停服。
还好,Apache Common Configuration给我们提供了可以检测文件修改后配置可短时间生效的功能。具体用法如下:
package com.netease.test.commons;import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.log4j.Logger;
/**
* User: hzwangxx
* Date: 14-3-13
* Time: 17:20
*/
public class SystemConfig {
private static Logger logger = Logger.getLogger(SystemConfig.class);
private static PropertiesConfiguration config;
static {
try {
//实例化一个PropertiesConfiguration
config = new PropertiesConfiguration("/Users/hzwangxx/IdeaProjects/app-test/src/main/resources/conf.properties");
//设置reload策略,这里用当文件被修改之后reload(默认5s中检测一次)
config.setReloadingStrategy(new FileChangedReloadingStrategy());
} catch (ConfigurationException e) {
logger.error("init static block error. ", e);
}
}
public static synchronized String getProperty(String key) {
return (String) config.getProperty(key);
}
public static void main(String[] args) throws InterruptedException {
for (;;) {
System.out.println(SystemConfig.getProperty("key"));
Thread.sleep(2000);
}
}
}
/*
output:
value
value
value
2014-03-13 17:54:37,251 12007 [main] INFO - Reloading configuration. URL is file:/Users/apple/IdeaProjects/app-test/src/main/resources/conf.properties
updateValue
updateValue
*/