我正在用java设计一个web服务,我需要用java中的请求进行某种AB测试。
基本上,我正在寻找轻松配置参数的方法,这些参数将由请求处理程序动态加载,以确定基于配置值的代码路径。
例如,假设我需要从外部 Web 服务或本地数据库获取一些数据。我希望有一种方法来配置参数(在此上下文中的条件),以便确定是从外部 Web 服务还是从本地数据库获取数据。
如果我使用上面示例的键值对配置系统可能会产生类似的结果。
locale=us
percentage=30
browser=firefox
这意味着我将从本地数据库获取来自用户代理为 Firefox 的美国用户的 30% 的请求数据。我希望这个配置系统是动态的,这样服务器就不需要重新启动。
对于非常高层次的描述感到抱歉,但任何见解/线索将不胜感激。 如果这是一个过去被打死的话题,请告诉我链接。
最佳答案
我以前用过这个。这是java中使用java.util.Properties实现您所要求的最常见的方法:
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());
}
}
}
然后在你的主类中你可以这样做:
Settings.load(); //Load settings
然后您可以检查每个其他类中这些变量的值,例如:
if (Settings.DEBUG) System.out.println("The debug value is true");
关于java - 在java中动态加载配置的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20963019/