这实际上取决于您希望重新加载属性的频率。我采取的一种方法是有一个属性文件包装器(单件),它具有一个可配置参数,用于定义文件应该重新加载的频率。然后我总是通过该包装器读取属性,并且它会在15分钟内重新加载属性(类似于Log4J的ConfigureAndWatch)。这样,如果我想,我可以在不更改已部署应用程序的状态的情况下更改属性。
这也允许您从数据库而不是文件加载属性。通过这种方式,您可以确信集群中各个节点的属性是一致的,并且可以降低与管理每个节点的配置文件相关的复杂性。
我更喜欢将它绑定到生命周期事件。如果你没有曾经打算改变他们,然后让他们静态常量的地方:)
下面是一个例子实施给你一个想法:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
/**
* User: jeffrey.a.west
* Date: Jul 1, 2011
* Time: 8:43:55 AM
*/
public class ReloadingProperties
{
private final String lockObject = "LockMe";
private long lastLoadTime = 0;
private long reloadInterval;
private String filePath;
private Properties properties;
private static final Map<String, ReloadingProperties> instanceMap;
private static final long DEFAULT_RELOAD_INTERVAL = 1000 * 60 * 5;
public static void main(String[] args)
{
ReloadingProperties props = ReloadingProperties.getInstance("myProperties.properties");
System.out.println(props.getProperty("example"));
try
{
Thread.sleep(6000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(props.getProperty("example"));
}
static
{
instanceMap = new HashMap(31);
}
public static ReloadingProperties getInstance(String filePath)
{
ReloadingProperties instance = instanceMap.get(filePath);
if (instance == null)
{
instance = new ReloadingProperties(filePath, DEFAULT_RELOAD_INTERVAL);
synchronized (instanceMap)
{
instanceMap.put(filePath, instance);
}
}
return instance;
}
private ReloadingProperties(String filePath, long reloadInterval)
{
this.reloadInterval = reloadInterval;
this.filePath = filePath;
}
private void checkRefresh()
{
long currentTime = System.currentTimeMillis();
long sinceLastLoad = currentTime - lastLoadTime;
if (properties == null || sinceLastLoad > reloadInterval)
{
System.out.println("Reloading!");
lastLoadTime = System.currentTimeMillis();
Properties newProperties = new Properties();
FileInputStream fileIn = null;
synchronized (lockObject)
{
try
{
fileIn = new FileInputStream(filePath);
newProperties.load(fileIn);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (fileIn != null)
{
try
{
fileIn.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
properties = newProperties;
}
}
}
public String getProperty(String key, String defaultValue)
{
checkRefresh();
return properties.getProperty(key, defaultValue);
}
public String getProperty(String key)
{
checkRefresh();
return properties.getProperty(key);
}
}
谢谢杰夫......你能告诉我一些实现吗?从数据库加载属性超出了此任务的范围。 –
添加代码示例。 –
感谢您的代码示例!我不知道我的领导是否希望像这样开箱即可......将建议给他。没有默认目录或只有简单的配置区域,WebLogic加载可供任何在WebLogic中运行的应用程序访问的属性文件? –