原文: https://howtodoinjava.com/java7/auto-reload-of-configuration-when-any-change-happen/

每当配置文件中发生任何更改时,都会自动刷新这些文件 – 这是大多数应用程序中常见的一个常见问题。 每个应用程序都有一些配置,预期该配置文件中的每次更改都会刷新。 解决该问题的过去方法包括使用Thread,它根据配置文件的最后更新时间戳定期轮询文件更改。

现在使用 Java 7,情况已经改变。 Java 7 引入了一项出色的特性:WatchService。 我将尽力为您解决上述问题。 这可能不是最好的实现,但是肯定会为您的解决方案提供一个很好的开始。 我敢打赌!

  1. Table of Contents:
  2. 1) A brief overview of WatchService
  3. 2) Writing our configuration provider
  4. 3) Introducing configuration change listener
  5. 4) Testing our code
  6. 5) Key notes

1. Java WatchService API

WatchService是 JDK 的内部服务,监视注册对象的更改。 这些注册的对象必定是Watchable接口的实例。 在WatchService中注册Watchable实例时,我们需要指定我们感兴趣的变更事件的类型。

到目前为止,有四种类型的事件:

  1. ENTRY_CREATE
  2. ENTRY_DELETE
  3. ENTRY_MODIFY
  4. OVERFLOW

您可以在提供的链接中了解这些事件。

WatchService接口扩展了Closeable接口,表示可以根据需要关闭服务。 通常,应该使用 JVM 提供的关闭挂钩来完成。

2. 应用程序配置供应器

配置供应器只是用于包装java.util.Properties实例中的属性集的包装器。 它还提供了使用来获取已配置属性的方法。

  1. package testWatchService;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.util.Properties;
  7. public class ApplicationConfiguration {
  8. private final static ApplicationConfiguration INSTANCE = new ApplicationConfiguration();
  9. public static ApplicationConfiguration getInstance() {
  10. return INSTANCE;
  11. }
  12. private static Properties configuration = new Properties();
  13. private static Properties getConfiguration() {
  14. return configuration;
  15. }
  16. public void initilize(final String file) {
  17. InputStream in = null;
  18. try {
  19. in = new FileInputStream(new File(file));
  20. configuration.load(in);
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. }
  24. }
  25. public String getConfiguration(final String key) {
  26. return (String) getConfiguration().get(key);
  27. }
  28. public String getConfigurationWithDefaultValue(final String key,
  29. final String defaultValue) {
  30. return (String) getConfiguration().getProperty(key, defaultValue);
  31. }
  32. }

3. 配置更改监听器 – 文件监视器

现在,当我们有了配置属性的内存中缓存的基本包装器时,我们需要一种机制,只要存储在文件系统中的配置文件发生更改,就可以在运行时重新加载此缓存。

我已经写了一个示例工作代码来为您提供帮助:

  1. package testWatchService;
  2. import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
  3. import java.io.IOException;
  4. import java.nio.file.FileSystems;
  5. import java.nio.file.Path;
  6. import java.nio.file.Paths;
  7. import java.nio.file.WatchEvent;
  8. import java.nio.file.WatchKey;
  9. import java.nio.file.WatchService;
  10. public class ConfigurationChangeListner implements Runnable {
  11. private String configFileName = null;
  12. private String fullFilePath = null;
  13. public ConfigurationChangeListner(final String filePath) {
  14. this.fullFilePath = filePath;
  15. }
  16. public void run() {
  17. try {
  18. register(this.fullFilePath);
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. private void register(final String file) throws IOException {
  24. final int lastIndex = file.lastIndexOf("/");
  25. String dirPath = file.substring(0, lastIndex + 1);
  26. String fileName = file.substring(lastIndex + 1, file.length());
  27. this.configFileName = fileName;
  28. configurationChanged(file);
  29. startWatcher(dirPath, fileName);
  30. }
  31. private void startWatcher(String dirPath, String file) throws IOException {
  32. final WatchService watchService = FileSystems.getDefault()
  33. .newWatchService();
  34. Path path = Paths.get(dirPath);
  35. path.register(watchService, ENTRY_MODIFY);
  36. Runtime.getRuntime().addShutdownHook(new Thread() {
  37. public void run() {
  38. try {
  39. watchService.close();
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. });
  45. WatchKey key = null;
  46. while (true) {
  47. try {
  48. key = watchService.take();
  49. for (WatchEvent<?> event : key.pollEvents()) {
  50. if (event.context().toString().equals(configFileName)) {
  51. configurationChanged(dirPath + file);
  52. }
  53. }
  54. boolean reset = key.reset();
  55. if (!reset) {
  56. System.out.println("Could not reset the watch key.");
  57. break;
  58. }
  59. } catch (Exception e) {
  60. System.out.println("InterruptedException: " + e.getMessage());
  61. }
  62. }
  63. }
  64. public void configurationChanged(final String file) {
  65. System.out.println("Refreshing the configuration.");
  66. ApplicationConfiguration.getInstance().initilize(file);
  67. }
  68. }

上面的类是使用线程创建的,该线程将使用WatchService监听配置属性文件的更改。

一旦检测到文件中的任何修改,它便会刷新配置中的内存缓存。

上述监听器的构造器仅采用一个参数,即受监视的配置文件的标准路径。 在文件系统中更改配置文件时,会立即通知Listener类。

然后,此监听器类调用ApplicationConfiguration.getInstance().initilize(file);以重新加载到内存缓存中。

4. 测试我们的代码

现在,当我们准备好类时,我们将对其进行测试。

首先,将test.properties文件及其以下内容存储在'C:/Lokesh/temp'文件夹中。

  1. TEST_KEY=TEST_VALUE

现在,让我们使用以下代码测试以上类。

  1. package testWatchService;
  2. public class ConfigChangeTest {
  3. private static final String FILE_PATH = "C:/Lokesh/temp/test.properties";
  4. public static void main(String[] args) {
  5. ConfigurationChangeListner listner = new ConfigurationChangeListner(
  6. FILE_PATH);
  7. try {
  8. new Thread(listner).start();
  9. while (true) {
  10. Thread.sleep(2000l);
  11. System.out.println(ApplicationConfiguration.getInstance()
  12. .getConfiguration("TEST_KEY"));
  13. }
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. }
  19. //Output of the above program (Change the TEST_VALUE to TEST_VALUE1 and TEST_VALUE2 using any file editor and save).
  20. Refreshing the configuration.
  21. TEST_VALUE
  22. TEST_VALUE
  23. TEST_VALUE
  24. Refreshing the configuration.
  25. TEST_VALUE1
  26. Refreshing the configuration.
  27. TEST_VALUE2

以上输出表明,每次我们对属性文件进行任何更改时,刷新的属性都会刷新,并且可以使用新的属性值。 到目前为止,已经做好了!

5. 重要说明

  1. 如果在新项目中使用 Java 7,并且没有在使用老式方法重新加载属性,则说明操作不正确。

  2. WatchService提供了两个方法take()poll()。当take()方法等待下一次更改发生并被阻止之前,poll()立即检查更改事件。
    如果上次poll()调用没有任何变化,它将返回 nullpoll()方法不会阻止执行,因此应在具有一些睡眠时间的线程中调用。

将我的问题/建议放在评论区。

学习愉快!