我有三种不同类型的服务器连接。这些可以在属性文件中配置。
假设有三台服务器:
Server1
Server2
Server3
In Properties
文件,我的配置如下:
ServerPref1 = Server1
ServerPref2 = Server2
ServerPref3 = Server3
在代码级别,我的回退机制如下:
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()
方法将抛出自定义ServerException
,如果无法连接到服务器。
一切都按预期进行。
我的问题是:这是实施后备机制的正确或最佳方法吗?
我建议您提供一个服务器连接列表,然后您可以使用循环而不是嵌套,这将允许您添加更多服务器而无需更改代码。
由于每个连接都有单独的属性,因此我可以提供的最好的方法是将这些字段放入临时列表中,然后在其上循环,而无需查看其余代码。
理想情况下,让您的属性解析代码也将连接写入列表中,这样您就可以拥有任意数量的服务器,而无需向 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
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)