当配置文件中发生任何更改时,自动刷新配置文件——这是大多数应用程序中常见的问题。每个应用程序都有一些配置,这些配置将在配置文件中的每次更改时刷新。过去解决这个问题的方法包括有一个线程,它根据配置文件的最后更新时间戳
定期轮询文件更改。
现在有了Java 7,一切都变了。Java 7引入了一个优秀的特性:WatchService
。我将试着给你一个解决上述问题的可能办法。这可能不是最好的实现,但它肯定会为您的解决方案提供一个良好的开端。我敢打赌! !
首先新建测试配置文件jdbc.properties
dbc.driver=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root
jdbc.className=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/bookstore
核心代码
public class Config {
private Properties properties = new Properties();
private AtomicBoolean isLoad = new AtomicBoolean(false);
public synchronized void load(String filePath) {
if (!isLoad.get()) {
try {
InputStream inputStream = new FileInputStream(filePath);
properties.load(inputStream);
isLoad.set(true);
new Thread(()->{
autoRefresh(filePath);
}).start();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("init error");
}
}
}
public void autoRefresh(String filePath) {
WatchService watchService;
try {
watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get(filePath);
path.getParent().register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
WatchKey key = watchService.take();
List<WatchEvent<?>> watchEvents = key.pollEvents();
for (WatchEvent<?> event : watchEvents) {
if (StandardWatchEventKinds.ENTRY_MODIFY == event.kind()) {
System.out.println("更新成功");
Properties refreshProperties = new Properties();
InputStream inputStream = new FileInputStream(filePath);
refreshProperties.load(inputStream);
properties.clear();
properties.putAll(refreshProperties);
}
}
key.reset();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Object getPropertie(String key) {
return properties.get(key);
}
}
测试代码
public class ConfigTest {
public static void main(String[] args) {
Config config = new Config();
config.load("C:\\Users\\EDENJIL\\Desktop\\jdbc.properties");
try {
while (true) {
Thread.sleep(2000l);
System.out.println(config.getPropertie("jdbc.url"));
System.out.println(config.getPropertie("a"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试代码如下图GIF