I'm using Java 8 (OpenJDK). It seems like the best way to disable dns cache in Java is to set networkaddress.cache.ttl=0
in $JAVA_HOME/jre/lib/security/java.security
.
I've tried that, but it seems to have no effect, no matter what value I put there, DNS entries are cached for ~5 seconds. I know that the value is set properly because I check it with java.security.Security.getProperty("networkaddress.cache.ttl")
.
I'm testing the java cache with a HttpURLConnection
client, and comparing it to a raw curl
client, curl doesn't cache at all. My server is a load balancer that returns one of 3 different ips for each request in round robin. Those ips each host a web service that returns the hostname it's running on.
This is how the my java client looks like:
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);
}
Which outputs:
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
And this is how my curl client looks like:
curl server
sleep 2s
curl server
sleep 4s
curl server
sleep 6s
curl server
sleep 11s
curl server
Which outputs:
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
What am I missing? Should I also configure something in HttpURLConnection
? Another jvm wide config? Maybe it's another cache, not a dns one, a connection pool or a socket pool?