不确定是否必须在另一个Stack Exchange站点中询问此问题,如果是,请相应地进行迁移!
我有三种不同类型的服务器连接.这些可以在属性文件中配置.
假设有三台服务器:
Server1
Server2
Server3
Run Code Online (Sandbox Code Playgroud)
在Properties文件中,我配置如下:
ServerPref1 = Server1
ServerPref2 = Server2
ServerPref3 = Server3
Run Code Online (Sandbox Code Playgroud)
在代码级别,我的后退机制如下:
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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果无法连接到服务器,该connect()方法将抛出自定义ServerException.
一切都按预期工作.
我的问题是:这是实现回退机制的正确或最佳方式吗?
我建议使用服务器连接列表,然后您可以使用循环而不是嵌套,这将允许您添加更多服务器而无需更改代码.
由于每个连接都有单独的属性,因此我可以提供的最佳属性,而不会看到其余的代码是将这些字段放入临时列表并循环遍历.
理想情况下,使您的属性解析代码也将连接写入List,这样您就可以拥有任意数量的服务器而无需向Properties类添加新字段.
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
}
}
}
Run Code Online (Sandbox Code Playgroud)