使用Apache背后的Tomcat设置,如何轻松确定服务器的id (理想情况下是IP地址)?
具体情况是,在负载均衡器后面设置了多个服务器,因此传入的请求主机名不是唯一的,不足以识别用于日志记录的特定服务器。不幸的是,使用HttpServletRequest.getLocalAddr()返回的是相同的主机名,而不是预期的IP地址(我假设这与这个非常老的问题有关:https://issues.apache.org/bugzilla/show_bug.cgi?id=46082)。
是否有办法使getLocalAddr()按照文档所述执行,或者是否需要其他方法来查询服务器的IP地址?
发布于 2013-02-09 06:31:36
对于我的情况,解决方案是直接获取服务器的IP地址,而不是尝试通过HttpServleRequest获取本地地址。
我通过以下方式缓存IP,以便在我的过滤器中使用:
private static final String serverIp;
static {
String addressString = null;
try
{
InetAddress address = InetAddress.getLocalHost();
addressString = address.getHostAddress();
} catch (Exception e)
{
logger.error("Exception while attempting to determine local ip address",e);
}
if (addressString != null) serverIp = addressString;
else serverIp = "unknown";
}发布于 2013-02-09 03:52:20
在我们的项目中,我们使用JMX来获取所有配置信息。这需要几个步骤,因为它类似于向下导航到server.xml文件,该链接包含一些信息:http://oss.wxnet.org/mbeans.html
如果你想要的只是IP,这可能有点夸张,但我想我还是把它扔出去吧。
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> theConnectors = mbeanServer.queryNames(
new ObjectName("Catalina:type=Connector,*"),
null);
if (theConnectors != null)
{
for (ObjectName nextConnectorName : theConnectors)
{
InetAddress theInetAddress = (InetAddress) mbeanServer.getAttribute(
nextConnectorName,
"address");
if (theInetAddress != null)
{
ipAddress = theInetAddress.getHostAddress();
}
if (!StringUtil.isEmpty(ipAddress))
{
// found the IP address
break;
}
}
}发布于 2019-08-30 18:36:57
我最近遇到了类似的问题(在最初的问题几年后),并找到了这个问题和答案。在我的例子中,问题是ServletRequest#getLocalAddr()实现返回的是远程地址,而不是本地地址。该问题是由Tomcat v9.0.22中的回归引起的。该问题已在v9.0.23中修复。请在此处查看问题和答案:
https://stackoverflow.com/questions/14780207
复制相似问题