这是我的问题:
我必须连接到代理服务(此处为 activemq),所以我这样做了:
public GenericMessageManager(String url, String producerQueue,
String consumerQueue) {
Connection connection;
try {
connection = getConnection(url);
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = createProducer(producerQueue);
consumer = createConsumer(consumerQueue);
connection.start();
logger.info("Connection to broker started");
} catch (JMSException e) {
}
}
private Connection getConnection(String url) {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
url);
try {
Connection connection = connectionFactory.createConnection();
return connection;
} catch (JMSException e) {
if (e.getLinkedException() instanceof SocketTimeoutException) {
logger.warn(url + " not responding, try on localhost");
getConnection("tcp://127.0.0.1:61616");
}
}
return null;
}
在 getConnection() 方法中,如果捕获 SocketTimeOutException,我会使用另一个 url 进行递归调用。这是可行的,但第一个调用在第二个调用之前返回 null,我在 connection.createSession(...); 上得到一个 NPE
我不知道我能做些什么来解决这个问题?
最佳答案
我不会通过递归来解决这个问题,因为直观上它似乎不是一个需要递归的问题。我宁愿配置有效主机的列表,并按顺序尝试它们,例如
for (String host : hosts) {
try {
Connection c = getConnection(host);
if (c != null) {
return c;
}
// log here (not sure I'd return null at all, mind)
}
catch (Exception e) {
// log here...
}
}
// fail completely
并且一致在失败的情况下抛出异常,而不是混淆异常和空值的含义/处理。
上面将连接的建立(和错误处理)与重试机制隔离开来,并且可以说使其更简单、更容易理解。
关于java - catch block 方法中的递归调用返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29796656/