Java:获取DNS负载均衡器后面的服务器的IP地址

时间:2017-01-16 09:16:09

标签: java

我使用主机名从客户端连接到服务器,如下所示: -

    HttpPost post = new HttpPost(serverUrl);
    post.setEntity(new StringEntity(jsonRequestString, ContentType.APPLICATION_JSON));
    HttpResponse response = httpClient.execute(post);
    int ret = response.getStatusLine().getStatusCode();

我正在使用org.apache.http.*个软件包。现在,服务器位于DNS负载均衡器后面,其中8个唯一的IP地址绑定到主机名。但我相信JVM的单次运行中的所有请求都将使用相同的IP地址。

  1. 有没有办法打印DNS解析后返回的实际IP?
  2. JVM是否进行本地DNS缓存?
  3. 修改

    networkaddress.cache.ttlnetworkaddress.cache.negative.ttl设为0并不起作用。要么我没有正确设置它们。

    public static void main(String[] args) throws Exception {
        java.security.Security.setProperty("networkaddress.cache.ttl", "0"); // no
        // cache
       java.security.Security.setProperty("networkaddress.cache.negative.ttl", "0"); // no
        while (true) {
            System.out.println(InetAddress.getByName("google.com"));
            Thread.sleep(100);
        }
    

    }

    输出:

    google.com/216.58.197.78
    google.com/216.58.197.78
    google.com/216.58.197.78
    google.com/216.58.197.78
    google.com/216.58.197.78
    google.com/216.58.197.78
    google.com/216.58.197.78
    google.com/216.58.197.78
    google.com/216.58.197.78
    google.com/216.58.197.78
    google.com/216.58.197.78
    ........
    ........
    

1 个答案:

答案 0 :(得分:2)

  

有没有办法打印DNS解析后返回的实际IP?

您可以尝试配置记录器并检查来自“org.apache.http.impl.conn.HttpClientConnectionOperator”的日志消息

Reference

  

JVM是否进行本地DNS缓存?

这取决于配置,但很可能是,请检查以下设置:

<强> networkaddress.cache.ttl     在java.security中指定,用于指示名称服务中成功进行名称查找的缓存策略。该值指定为整数,表示缓存成功查找的秒数。

值-1表示“永远缓存”。默认行为是在安装安全管理器时永久缓存,并在未安装安全管理器时缓存特定于实现的时间段。

networkaddress.cache.negative.ttl (默认值:10) 在java.security中指定,用于指示名称服务中未成功名称查找的缓存策略。该值指定为整数,表示缓存未成功查找失败的秒数。

值为0表示“从不缓存”。值-1表示“永远缓存”。

Reference

<强>更新

您是否尝试直接调用API以将主机名解析为所有IP地址?

InetAddress.getAllByName(host)

来自javadocs

  

给定主机的名称,返回其IP地址的数组   在系统上配置的名称服务上。

另外interesting article on this topic(我自己未尝试过)

相关问题