/**
*
*/
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Objects;
import java.util.Properties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
/**
* @description
* @author Abel.li
* @version
*/
public class PropertiesUtil {
private static Properties properties;
static {
try {
final WatchService watchService = FileSystems.getDefault().newWatchService();
final String fileName = "abel.properties";
final Resource resource = new ClassPathResource(fileName);
Paths.get(resource.getFile().getParent()).register(watchService,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_CREATE);
properties = PropertiesLoaderUtils.loadProperties(resource);
Thread watchThread = new Thread(new Runnable() {
public void run() {
while(true){
try {
WatchKey watchKey = watchService.take();
watchLoop:for(WatchEvent<?> event : watchKey.pollEvents()){
if(Objects.equals(event.context().toString(), fileName)){
properties = PropertiesLoaderUtils.loadProperties(resource);
break watchLoop;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
watchThread.setDaemon(true);
watchThread.start();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
try {
watchService.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}));
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getValue(String key){
return properties.getProperty(key);
}
}
参考《亿级流量网站架构核心技术》
Properties 文件变更
最新推荐文章于 2023-03-14 20:56:44 发布