1. 程式人生 > >Java Configuration Manager Automatic Reloading

Java Configuration Manager Automatic Reloading

from rest call .com change for guide sed log

公司一個項目的從另外一個小公司,拷貝了一個PropertyParser的類,實現的有問題,必須重啟java應用才能讀取新的配置。

簡單的解決辦法,就是每次讀任何配置項時,都重新加載xxx.property文件,但是明顯不如當年C#的ConfigurationManager好用。

https://stackoverflow.com/questions/20661612/java-equivalent-for-cs-configurationmanager-appsettingsx

這篇文章,只回答了web的,沒有針對desktop和console類型的解答。

http://blog.163.com/s_zhchluo/blog/static/15014708200732191454527/

這篇文章提到了 Apache Commons Configuration項目,也解釋了其功能原理,很符合我的要求。

https://commons.apache.org/proper/commons-configuration/

The Commons Configuration software library provides a generic configuration interface which enables a Java application to read configuration data from a variety of sources.

望文生義,就是通用的配置庫,很不錯。

http://commons.apache.org/proper/commons-configuration/userguide_v1.10/howto_filebased.html

節選Automatic Reloading部分的說明:

Automatic Reloading

A common issue with file-based configurations is to handle the reloading of the data file when it changes. This is especially important if you have long running applications and do not want to restart them when a configuration file was updated. Commons Configuration has the concept of so called reloading strategies

that can be associated with a file-based configuration. Such a strategy monitors a configuration file and is able to detect changes. A default reloading strategy is FileChangedReloadingStrategy. It can be set on a file-based configuration as follows:


PropertiesConfiguration config = new PropertiesConfiguration("usergui.properties");
config.setReloadingStrategy(new FileChangedReloadingStrategy());

FileChangedReloadingStrategy works as follows: On every property access the configuration checks its associated reloading strategy. FileChangedReloadingStrategy will then obtain the last modification date of the configuration file and check whether it has changed since the last access. If this is the case, a reload is triggered. To avoid often disk access when multiple properties are queried from the configuration, a refresh delay can be set on the reloading strategy. This is a time in milli seconds with the meaning that the reloading strategy will only once check the file‘s last modification time in the period specified here.

每一次屬性訪問時,都會檢查文件,如果最後訪問時間有變化,則自動重新載入。為了減少硬盤訪問頻率,又添加了"刷新延遲(設定刷新延遲時間)"機制。上述機制基於commons-configuration/userguide_v1.10。

還有一篇介紹如何實現重載機制的文章,講解了其他重載機制。

https://commons.apache.org/proper/commons-configuration/userguide/howto_reloading.html

Java Configuration Manager Automatic Reloading