java实现清理DNS Cache的方法
本文实例讲述了java实现清理DNSCache的方法。分享给大家供大家参考。具体分析如下:
一、测试环境
OS:Windows7x64
JDK:1.6.0_45
二、本人找到四种方式清理jvm的DNS缓存,大家可以根据自己的情况选用。
1.在首次调用InetAddress.getByName()前,设置java.security.Security.setProperty("networkaddress.cache.ttl","0");
2.修改jre/lib/security/java.security下的networkaddress.cache.ttl属性
3.jvm启动参数中设置-Dsun.net.inetaddr.ttl=0
4.通过反射清理,如本文的clearCache方法
三、代码
packagexiaofei; importjava.lang.reflect.Field; importjava.net.InetAddress; importjava.net.UnknownHostException; importjava.util.Map; /** *@authorxiaofei.wxf *@date13-12-18 */ publicclassDNSCacheTest{ /** *1.在首次调用InetAddress.getByName()前,设置java.security.Security.setProperty("networkaddress.cache.ttl","0"); *2.修改jre/lib/security/java.security下的networkaddress.cache.ttl属性 *3.jvm启动参数中设置-Dsun.net.inetaddr.ttl=0 *4.调用clearCache方法清除 * *@paramargs *@throwsUnknownHostException */ publicstaticvoidmain(String[]args)throwsUnknownHostException,NoSuchFieldException,IllegalAccessException{ java.security.Security.setProperty("networkaddress.cache.ttl","0"); InetAddressaddr1=InetAddress.getByName("www.baidu.com"); System.out.println(addr1.getHostAddress()); //clearCache(); //在下一行设置断点. //放在此处无效,因为类加载的时候就确定了这个值(应该在使用InetAddress.getByName之前设置)已经缓存了cache //java.security.Security.setProperty("networkaddress.cache.ttl","0"); InetAddressaddr2=InetAddress.getByName("www.baidu.com"); System.out.println(addr2.getHostAddress()); InetAddressaddr3=InetAddress.getByName("www.google.com"); System.out.println(addr3.getHostAddress()); InetAddressaddr4=InetAddress.getByName("www.google.com"); System.out.println(addr4.getHostAddress()); //clearCache(); } publicstaticvoidclearCache()throwsNoSuchFieldException,IllegalAccessException{ //修改缓存数据开始 Classclazz=java.net.InetAddress.class; finalFieldcacheField=clazz.getDeclaredField("addressCache"); cacheField.setAccessible(true); finalObjectobj=cacheField.get(clazz); ClasscacheClazz=obj.getClass(); finalFieldcachePolicyField=cacheClazz.getDeclaredField("type"); finalFieldcacheMapField=cacheClazz.getDeclaredField("cache"); cachePolicyField.setAccessible(true); cacheMapField.setAccessible(true); finalMapcacheMap=(Map)cacheMapField.get(obj); System.out.println(cacheMap); cacheMap.remove("www.baidu.com"); } }
希望本文所述对大家的Java程序设计有所帮助。