在java中动态加载配置的最佳方法?

Pro*_*ter 1 java config ab-testing

我正在用 Java 设计一个 Web 服务,我需要在其中对 Java 中的请求进行某种 AB 测试。

基本上,我正在寻找轻松配置参数的方法,这些参数将由请求处理程序动态加载,以确定基于配置值的代码路径。

例如,假设我需要从外部 Web 服务或本地数据库获取一些数据。我想有一种方法来配置参数(此上下文中的标准),以便它确定是从外部 Web 服务还是从本地数据库获取数据。

如果我使用上面示例中的键值对配置系统,可能会产生类似的结果。

locale=us
percentage=30
browser=firefox
Run Code Online (Sandbox Code Playgroud)

这意味着我将从本地数据库中获取 30% 来自用户代理为 firefox 的美国用户的请求的数据。我希望这个配置系统是动态的,这样服务器就不需要重新启动。

对非常高级的描述感到抱歉,但任何见解/线索将不胜感激。如果这是一个过去被殴打致死的话题,请告诉我链接。

Bra*_*ger 5

我过去用过这个。这是使用 java.util.Properties 实现您所要求的 Java 中最常见的方法:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
* Class that loads settings from config.properties
* @author Brant Unger
*
*/
public class Settings 
{
public static boolean DEBUG = false; 

/**
 * Load settings from config.properties
 */
public static void load()
{
    try
    {
        Properties appSettings = new Properties();
        FileInputStream fis = new FileInputStream("config.properties"); //put config properties file to buffer
        appSettings.load(fis); //load config.properties file

                   //This is where you add your config variables:
                   DEBUG = Boolean.parseBoolean((String)appSettings.get("DEBUG"));

        fis.close();
        if(DEBUG) System.out.println("Settings file successfuly loaded");

    }
    catch(IOException e)
    {
        System.out.println("Could not load settings file.");
        System.out.println(e.getMessage());
    }
}
Run Code Online (Sandbox Code Playgroud)

}

然后在您的主课程中,您可以执行以下操作:

Settings.load(); //Load settings
Run Code Online (Sandbox Code Playgroud)

然后,您可以在每个其他类中检查这些变量的值,例如:

if (Settings.DEBUG) System.out.println("The debug value is true");
Run Code Online (Sandbox Code Playgroud)