用Java可以做到吗?连接字符串中的主机无法解析,因此在能够在连接上调用getMetaData之前,我在DataSource的getConnection()中获取了SQLException。
这是我的代码:
DataSource ds = null;
Connection connection = null;
DataSourceProbeRequest request = null;
try {
request = (DataSourceProbeRequest) probeRequest;
ds = request.getDataSource();
connection = ds.getConnection();
final boolean validConnection = connection != null && connection.isValid(5000);
if (validConnection) {
LOGGER.info("Connection is ok: " + request.getTargetId());
return new ProbeResult(request.getTargetId(), buildDatasourceMsg(connection, true));
} else {
return new ProbeResult(request.getTargetId(), new Exception(buildDatasourceMsg(connection, false)));
}
} catch (Exception exp) {
return new ProbeResult(request.getTargetId(), exp);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
LOGGER.warn("Failed to close database connection", e);
}
}
}
由于主机不可访问,connection = ds.getConnection();将引发异常并导致new
ProbeResult(request.getTargetId(), exp)返回。但是,该异常仅具有诸如之类的错误消息IO Error: The
Network Adapter could not establish the
connection。它没有在连接字符串中给出主机名。我想显示主机名(或连接字符串)以便可以对其进行诊断