Java進程配置文件Reload


  我們在開發Java程序的時候,很多常量信息都存在配置文件中,比如數據庫連接信息、ip黑名單,事件的超時時間等等。當需要該這些配置的值時都需要重新啟動進程,改動的配置才會生效,有時候線上的應用不能容忍這種停服。

  還好,Apache Common Configuration給我們提供了可以檢測文件修改后配置可短時間生效的功能。具體用法如下:

package com.netease.test.commons;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.log4j.Logger;

/**
 * User: hzwangxx
 * Date: 14-3-13
 * Time: 17:20
 */
public class SystemConfig {
    private static Logger logger = Logger.getLogger(SystemConfig.class);

    private static  PropertiesConfiguration config;

    static {
        try {
            //實例化一個PropertiesConfiguration
            config = new PropertiesConfiguration("/Users/hzwangxx/IdeaProjects/app-test/src/main/resources/conf.properties");
            //設置reload策略,這里用當文件被修改之后reload(默認5s中檢測一次)
            config.setReloadingStrategy(new FileChangedReloadingStrategy());
        } catch (ConfigurationException e) {
            logger.error("init static block error. ", e);
        }
    }

    public static synchronized String getProperty(String key) {
        return (String) config.getProperty(key);
    }

    public static void main(String[] args) throws InterruptedException {
        for (;;) {
            System.out.println(SystemConfig.getProperty("key"));
            Thread.sleep(2000);
        }
    }

}

/*
output:
value
value
value
2014-03-13 17:54:37,251 12007 [main] INFO  - Reloading configuration. URL is file:/Users/apple/IdeaProjects/app-test/src/main/resources/conf.properties
updateValue
updateValue
 */

這個比較實用,贊一個,牛刀小試了一把。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM