简体   繁体   中英

Changing JAVA DNS Cache settings

I am using java8 for my web application. I would like to change the settings of JAVA DNS Cache. This is the code:

java.security.Security.setProperty("networkaddress.cache.ttl", "60");
java.security.Security.setProperty("sun.net.inetaddr.negative.ttl", "10");

I would like to know where exactly I should write the code (in which class file) to reflect the changes in JVM before DNS chance gets initialised.

I would like to make the change using a java utility class file.Please suggest for the same. And also suggest how to configure the same change in build.xml(ant)?

I agree with answers updated where they have suggested to change security file.But i would like to know the configuration in other ways too due to limitations that i have in my project.

You can also set it globally by add this line

networkaddress.cache.ttl=60

to $JAVA_HOME/jre/lib/security/java.security file.

Your best bet is to set it directly in the java.security file located in /lib/security

Note: if you are using a shared JVM, you'll need to set this in your startup command -Djava.security.properties=/DirectoryPath/filename and set the value of security.overridePropertiesFile to true.

If you want to set this in code then you have a number of options - you just need to put the code in a place that you know will be executed before the first message is processed after application startup.

My preference would be to register a ContextListener and put the code in there.

I encountered a similar issue where my java application wouldn't resolve the URL. In addition to what is suggested ( ie,networkaddress.cache.ttl and networkaddress.cache.negative.ttl) I had to reset the caches in the URL Object.

URL url = new URL(urlSrt);
URLConnection con = url.openConnection();
con.setUseCaches(false);

I am not aware of (build.xml)ant. I will still give it a try just in case you are using spring framework. Following is what I did to set the networkaddress.cache.ttl at the time of application initialisation.

  1. Define a new Java class as follows.

     package com.example.util; public class SecurityManager { public SecurityManager() { java.security.Security.setProperty("networkaddress.cache.ttl", "60"); } } 
  2. Ask spring framework to instantiate the object of above class as a singleton at the time on spring container creation.

     <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="securityManager" class="com.example.util.SecurityManager" scope="singleton" /> </beans> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM