【问题标题】:disabling Java DNS cache禁用 Java DNS 缓存
【发布时间】:2019-08-04 11:14:55
【问题描述】:

我正在使用 Java 8 (OpenJDK)。在 Java 中禁用 dns 缓存的最佳方法似乎是在 $JAVA_HOME/jre/lib/security/java.security 中设置 networkaddress.cache.ttl=0

我已经尝试过了,但似乎没有任何效果,无论我放什么值,DNS 条目都会缓存约 5 秒。我知道该值设置正确,因为我使用java.security.Security.getProperty("networkaddress.cache.ttl") 检查它。

我正在使用HttpURLConnection 客户端测试java 缓存,并将其与原始curl 客户端进行比较,curl 根本不缓存。我的服务器是一个负载均衡器,它为循环中的每个请求返回 3 个不同的 ip 之一。这些 ips 每个都托管一个 Web 服务,该服务返回它正在运行的主机名。

这就是我的 java 客户端的样子:

    public static void main(String[] args) throws Exception {
        System.out.println("networkaddress.cache.ttl=" + java.security.Security.getProperty("networkaddress.cache.ttl"));
        Thread.sleep(1000);
        printServerHost();
        Thread.sleep(2000);
        printServerHost();
        Thread.sleep(4000);
        printServerHost();
        Thread.sleep(6000);
        printServerHost();
        Thread.sleep(11000);
        printServerHost();
    }

    public static void printServerHost() throws Exception{
        URL url = new URL("http://server/");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Cache-Control", "no-cache");
        con.setRequestProperty("accept", "application/json");

        BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String response = reader.readLine();
        reader.close();
        con.disconnect();

        System.out.println(response);
    }

哪些输出:

networkaddress.cache.ttl=0
ip-172-31-12-68.ec2.internal
ip-172-31-12-68.ec2.internal
ip-172-31-12-68.ec2.internal
ip-172-31-41-56.ec2.internal
ip-172-31-16-34.ec2.internal

这就是我的 curl 客户端的样子:

curl server
sleep 2s
curl server
sleep 4s
curl server
sleep 6s
curl server
sleep 11s
curl server

哪些输出:

ip-172-31-41-56.ec2.internal
ip-172-31-16-34.ec2.internal
ip-172-31-12-68.ec2.internal
ip-172-31-41-56.ec2.internal
ip-172-31-16-34.ec2.internal

我错过了什么?我还应该在HttpURLConnection 中配置一些东西吗?另一个jvm范围的配置?也许它是另一个缓存,而不是 dns 缓存、连接池或套接字池?

【问题讨论】:

    标签: java http dns network-programming round-robin


    【解决方案1】:

    问题是另一个缓存,与 dns 无关,可能在连接或套接字中,因为使用 ForkJoinPool 显示不同的主机:

    ForkJoinPool forkJoinPool = new ForkJoinPool(3);        
    forkJoinPool.submit(() -> IntStream.range(0, 10).parallel().forEach(i -> printServerHost())).get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-22
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-01
      • 2012-07-27
      • 1970-01-01
      相关资源
      最近更新 更多