java完成清算DNS Cache的辦法。本站提示廣大學習愛好者:(java完成清算DNS Cache的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是java完成清算DNS Cache的辦法正文
本文實例講述了java完成清算DNS Cache的辦法。分享給年夜家供年夜家參考。詳細剖析以下:
1、測試情況
OS:Windows7 x64
JDK:1.6.0_45
2、自己找到四種方法清算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辦法
3、代碼
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. 在初次挪用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辦法消除
*
* @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.百度.com");
System.out.println(addr1.getHostAddress());
//clearCache();
//鄙人一行設置斷點.
//放在此處有效,由於類加載的時刻就肯定了這個值(應當在應用InetAddress.getByName之前設置)曾經緩存了cache
//java.security.Security.setProperty("networkaddress.cache.ttl", "0");
InetAddress addr2 = InetAddress.getByName("www.百度.com");
System.out.println(addr2.getHostAddress());
InetAddress addr3 = InetAddress.getByName("www.谷歌.com");
System.out.println(addr3.getHostAddress());
InetAddress addr4 = InetAddress.getByName("www.谷歌.com");
System.out.println(addr4.getHostAddress());
//clearCache();
}
public static void clearCache() throws NoSuchFieldException, IllegalAccessException {
//修正緩存數據開端
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.百度.com");
}
}
願望本文所述對年夜家的Java法式設計有所贊助。