问题
Not sure if this question has to be asked in another Stack Exchange site, if so please migrate accordingly!
I have three different types of server connection. These can be configured in properties file.
Say there are three servers:
Server1
Server2
Server3
In Properties
file, I've configured as below:
ServerPref1 = Server1
ServerPref2 = Server2
ServerPref3 = Server3
In code level, my fall back mechanism is as below:
private static void getServerAndConnect() {
try {
connect(Properties.ServerPref1);
} catch (ServerException se1) {
try {
connect(Properties.ServerPref2);
} catch (ServerException se2) {
try {
connect(Properties.ServerPref3);
} catch (ServerException se3) {
// Unable to connect
}
}
}
}
The connect()
method will throw custom ServerException
, if unable to connect to server.
Everything works as expected.
My question is: Is this the correct or best way to implement fallback mechanism?
回答1:
I'd recommend a list of server connections then you can use a loop instead of nesting, this will let you add more servers without code changes.
Since you have separate attributes for each connection the best I can offer without seeing the rest of your code is to put those fields into a temporary list and loop over that.
Ideally make your properties parsing code write the connections into a List as well so you can have arbitrary number of servers without adding new fields to your Properties class.
private static void getServerAndConnect() {
List<ServerPref> serverPrefs = Arrays.asList(Properties.ServerPref1, Properties.ServerPref2, Properties.ServerPref3);
for (ServerPref serverPref : serverPrefs) {
try {
connect(serverPref);
// test success of connection? and break out of the loop
break;
} catch (ServerException se1) {
// log error and go onto next one
}
}
}
回答2:
The general approach is ok. Depending on your needs you could make a few improvements:
Are there always exactly three servers? If than number can change, put your servers in a list, and iterate over that list to find the first functioning server.
If you want your work load more evenly distributed over the servers, instead of all connections going to the first server if it is available, randomize the list of servers before you iterate ofver it, or use a round robin approach.
If the getServerAndConnect() method is called often, consider remembering the server that was used eventually, and use that first the next time, since the probability is hight that is still is reachable.
来源:https://stackoverflow.com/questions/25967212/fallback-mechanism-best-approach