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
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值