i am designing a web service in java where i need to do a sort of AB testing with requests in java.
Basically I’m looking for ways to easily configure parameters which will be dynamically loaded by a request handler to determine the code path based on config values.
for example, let’s say i need to get some data either from an external web service or from local DB. i want to have a way to configure parameters(criteria in this context) so that it would determine whether to go fetch data from external web service or from local DB.
if i go with a key-value pair config system above example might produce something like this.
locale=us percentage=30 browser=firefox
which would mean that i would be fetching data from local DB for 30% of requests from US users whose user-agent is firefox. and i would like this config system to be dynamic so that server does not need to be restarted.
sorry about very high level description but any insights/leads would be appreciated. if this is a topic that is beaten to death in the past, please kindly let me know the links.
Advertisement
Answer
I’ve used this in the past. It is the most common way in java to achieve what you are asking using 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()); } }
}
Then in your main class you can do:
Settings.load(); //Load settings
Then you can check the values of those variables in every other class like:
if (Settings.DEBUG) System.out.println("The debug value is true");