java7 WatchService 您用過嗎?

每當這些文件發生任何更改時,它們都會自動刷新 -這是大多數應用程序中常見的非常普遍的問題。每個應用程序都有一些配置,預期該配置文件中的每次更改都會刷新。解決該問題的過去方法包括使用Thread,根據配置文件的“ 最後更新時間戳 ” 定期輪詢文件更改。
現在使用Java 7,情況已經改變。Java 7引入了一項出色的功能:WatchService。我將盡力爲您解決上述問題。這可能不是最好的實現,但是肯定會爲您的解決方案提供一個很好的開始。我敢打賭!

1.Java WatchService API

A WatchService是JDK的內部服務,它監視註冊對象的更改。這些註冊的對象必須是Watchable接口的實例。在向中註冊可監視實例時WatchService,我們需要指定我們感興趣的變更事件的類型。
到目前爲止,有四種類型的事件:

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

WatchServiceinterface擴展了Closeable接口,表示可以在需要時關閉服務。通常,應該使用JVM提供的關閉掛鉤來完成。

2.應用程序配置提供程序

配置提供程序只是用於包裝java,util.Properties實例中的屬性集的包裝器。它還提供了使用KEY來獲取配置屬性的方法。

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
 
public class ApplicationConfiguration {
    private final static ApplicationConfiguration INSTANCE = new ApplicationConfiguration();
 
    public static ApplicationConfiguration getInstance() {
        return INSTANCE;
    }
 
    private static Properties configuration = new Properties();
 
    private static Properties getConfiguration() {
        return configuration;
    }
 
    public void initilize(final String file) {
        InputStream in = null;
        try {
            in = new FileInputStream(new File(file));
            configuration.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public String getConfiguration(final String key) {
        return (String) getConfiguration().get(key);
    }
 
    public String getConfigurationWithDefaultValue(final String key,
            final String defaultValue) {
        return (String) getConfiguration().getProperty(key, defaultValue);
    }
}

3.配置更改偵聽器– File Watcher

現在,當我們有了配置屬性的內存中高速緩存的基本包裝器時,我們需要一種機制,只要存儲在文件系統中的配置文件發生更改,就可以在運行時重新加載此高速緩存。
我已經寫了一個示例工作代碼來爲您提供幫助:

 
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
 
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
 
public class ConfigurationChangeListner implements Runnable {
    private String configFileName = null;
    private String fullFilePath = null;
 
    public ConfigurationChangeListner(final String filePath) {
        this.fullFilePath = filePath;
    }
 
    public void run() {
        try {
            register(this.fullFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    private void register(final String file) throws IOException {
        final int lastIndex = file.lastIndexOf("/");
        String dirPath = file.substring(0, lastIndex + 1);
        String fileName = file.substring(lastIndex + 1, file.length());
        this.configFileName = fileName;
 
        configurationChanged(file);
        startWatcher(dirPath, fileName);
    }
 
    private void startWatcher(String dirPath, String file) throws IOException {
        final WatchService watchService = FileSystems.getDefault()
                .newWatchService();
        Path path = Paths.get(dirPath);
        path.register(watchService, ENTRY_MODIFY);
 
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                try {
                    watchService.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
 
        WatchKey key = null;
        while (true) {
            try {
                key = watchService.take();
                for (WatchEvent<?> event : key.pollEvents()) {
                    if (event.context().toString().equals(configFileName)) {
                        configurationChanged(dirPath + file);
                    }
                }
                boolean reset = key.reset();
                if (!reset) {
                    System.out.println("Could not reset the watch key.");
                    break;
                }
            } catch (Exception e) {
                System.out.println("InterruptedException: " + e.getMessage());
            }
        }
    }
 
    public void configurationChanged(final String file) {
        System.out.println("Refreshing the configuration.");
        ApplicationConfiguration.getInstance().initilize(file);
    }
}

上面的類是使用線程創建的,該線程將使用偵聽配置屬性文件的更改WatchService
一旦檢測到文件中的任何修改,它便會刷新配置中的內存緩存。
上述偵聽器的構造函數僅採用一個參數,即受監視的配置文件的標準路徑。Listener在文件系統中更改配置文件時,將立即通知類。
然後,此偵聽器類調用ApplicationConfiguration.getInstance().initilize(file);以重新加載到內存緩存中。

4.測試我們的代碼

現在,當我們準備好上課時,我們將對其進行測試。
首先,將test.properties具有以下內容的'C:/Lokesh/temp'文件存儲在文件夾中。

TEST_KEY = TEST_VALUE

現在,讓我們使用以下代碼測試以上類。

public class ConfigChangeTest {
    private static final String FILE_PATH = "C:/Lokesh/temp/test.properties";
 
    public static void main(String[] args) {
        ConfigurationChangeListner listner = new ConfigurationChangeListner(
                FILE_PATH);
        try {
            new Thread(listner).start();
            while (true) {
                Thread.sleep(2000l);
                System.out.println(ApplicationConfiguration.getInstance()
                        .getConfiguration("TEST_KEY"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
//Output of the above program (Change the TEST_VALUE to TEST_VALUE1 and TEST_VALUE2 using any file editor and save).
 
Refreshing the configuration.
 
TEST_VALUE
 
TEST_VALUE
 
TEST_VALUE
 
Refreshing the configuration.
 
TEST_VALUE1
 
Refreshing the configuration.
 
TEST_VALUE2

以上輸出顯示,每次我們對屬性文件進行任何更改時,加載的屬性都會刷新,並且可以使用新的屬性值。到目前爲止,已經做好了!

5.重要說明

  1. 如果在新項目中使用Java 7,並且沒有在使用老式方法重新加載屬性,則說明操作不正確。
  2. WatchService提供兩種方法take()和poll()。在take()方法等待下一個更改發生並被阻止之前,請poll()立即檢查更改事件。如果上次poll()調用沒有任何變化,它將返回null。poll()方法不會阻止執行,因此應在具有一定睡眠時間的線程中調用該方法。

在評論區域中將您的問題/建議交給我。
學習愉快!

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