闲的蛋疼,自己写小项目。自动加载一些配置需要这么个东西。
监听目录下的文件变化,读取配置。
class="java">
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.*;
import java.util.Properties;
@Slf4j
@Component
@Scope("singleton")
public class ConfigUtil {
private final static Properties properties = new Properties();
static {
final WatchService[] watchService = {null};
new Thread(()->{
try {
String configFile = System.getProperty("config.file", "/tmp/config.properties");
log.info("loading config file {}.", configFile);
properties.load(new FileInputStream(configFile));
Path configFilePath = Paths.get(configFile);
watchService[0] = Filesystems.html" target="_blank">Systems.getDefault().newWatchService();
final Path path = Paths.get(configFilePath.getParent().toString());
path.register(watchService[0], StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE);
while (true) {
final WatchKey wk = watchService[0].take();
for (WatchEvent<?> event : wk.pollEvents()) {
final Path changed = (Path) event.context();
log.info(changed + ", " + event.kind());
if (changed.endsWith(configFilePath.getFileName())) {
log.info("reload config file {}.", configFile);
properties.load(new FileInputStream(configFile));
}
}
boolean valid = wk.reset();
if (!valid) {
log.info("Key has been unregistered.");
}
}
}catch (Exception e){
log.info("", e);
}
}).start();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try{
watchService[0].close();
} catch(IOException e) {
e.printStackTrace();
}
}));
}
public static Object get(String key){
return properties.get(key);
}
public static String stringValue(String key){
return properties.getProperty(key);
}
public static String stringValue(String key, String defaultValue){
return properties.getProperty(key, defaultValue);
}
}