This article illustrates the Java implementation method to clean up DNS cache. Share to everyone for your reference. The specific analysis is as follows:
First, test environment
Os:windows7 x64
Jdk:1.6.0_45
Second, I found four ways to clean up the JVM's DNS cache, we can choose according to their own situation.
1. Before the first call to Inetaddress.getbyname (), set the Java.security.Security.setProperty ("Networkaddress.cache.ttl", "0");
2. Modify the Networkaddress.cache.ttl properties under Jre/lib/security/java.security
3. Setting-dsun.net.inetaddr.ttl=0 in JVM startup parameters
4. Through reflection cleaning, such as the ClearCache method of this article
Third, the Code
Copy Code code as follows:
Package Xiaofei;
Import Java.lang.reflect.Field;
Import java.net.InetAddress;
Import java.net.UnknownHostException;
Import Java.util.Map;
/**
* @author XIAOFEI.WXF
* @date 13-12-18
*/
public class Dnscachetest {
/**
* 1. Before the first call to Inetaddress.getbyname (), set the Java.security.Security.setProperty ("Networkaddress.cache.ttl", "0");
* 2. To modify the Networkaddress.cache.ttl properties under Jre/lib/security/java.security
* 3. Set-dsun.net.inetaddr.ttl=0 in JVM startup parameters
* 4. Call the ClearCache method to clear the
*
* @param args
* @throws unknownhostexception
*/
public static void Main (string[] args) throws Unknownhostexception, Nosuchfieldexception, illegalaccessexception {
Java.security.Security.setProperty ("Networkaddress.cache.ttl", "0");
InetAddress ADDR1 = Inetaddress.getbyname ("www.baidu.com");
System.out.println (Addr1.gethostaddress ());
ClearCache ();
Set breakpoints on the next line.
This is not valid because the class is loaded with this value (which should be set before using Inetaddress.getbyname) that has cached the cache
Java.security.Security.setProperty ("Networkaddress.cache.ttl", "0");
InetAddress ADDR2 = Inetaddress.getbyname ("www.baidu.com");
System.out.println (Addr2.gethostaddress ());
InetAddress ADDR3 = Inetaddress.getbyname ("www.google.com");
System.out.println (Addr3.gethostaddress ());
InetAddress ADDR4 = Inetaddress.getbyname ("www.google.com");
System.out.println (Addr4.gethostaddress ());
ClearCache ();
}
public static void ClearCache () throws Nosuchfieldexception, Illegalaccessexception {
Modify cached data start
Class clazz = Java.net.InetAddress.class;
Final Field Cachefield = Clazz.getdeclaredfield ("Addresscache");
Cachefield.setaccessible (TRUE);
Final Object obj = Cachefield.get (clazz);
Class Cacheclazz = Obj.getclass ();
Final Field Cachepolicyfield = Cacheclazz.getdeclaredfield ("type");
Final Field Cachemapfield = Cacheclazz.getdeclaredfield ("cache");
Cachepolicyfield.setaccessible (TRUE);
Cachemapfield.setaccessible (TRUE);
Final Map Cachemap = (Map) cachemapfield.get (obj);
System.out.println (CACHEMAP);
Cachemap.remove ("www.baidu.com");
}
}
I hope this article will help you with your Java programming.