Java WatchService示例自動重新加載屬性

當配置文件中發生任何更改時,自動刷新配置文件——這是大多數應用程序中常見的問題。每個應用程序都有一些配置,這些配置將在配置文件中的每次更改時刷新。過去解決這個問題的方法包括有一個線程,它根據配置文件的最後更新時間戳定期輪詢文件更改。
現在有了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
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章