我们通常会遇到这样的需求,修改配置文件后不需要重启项目即可生效,此时我们需要去监听配置文件是否有被修改,如果发现被修改,那么我们即可重新加载配置文件。
public class Doctor {
private static final Logger LOGGER = Logger.getLogger(Doctor.class);
// update flag
protected static long lastModifiedDate = -1;
public static Properties PROPERTIES = new Properties();
public static void updateDoctor() {
new Thread(() -> {
try {
File file = new File=("F:\\doctor.properties");
while (true) {
try {
//如果时间戳不相等说明文件发生了修改
if (lastModifiedDate != file.lastModified()) {
//重新加载文件
try (FileInputStream fileInputStream = new FileInputStream(file);) {
PROPERTIES.load(fileInputStream);
//执行业务操作
}
lastModifiedDate = file.lastModified();
}
} catch (IOException e) {
LOGGER.error(e);
}
try {
//监听的时间间隔设置为1秒
Thread.sleep(1000);
} catch (InterruptedException e) {
LOGGER.error(e);
}
}
} catch (IOException e1) {
LOGGER.error(e1);
}
}).start();
}
}
我们只需在项目启动后调用该方法Doctor.updateDoctor();