项目组遇到服务器无法解析localhost的问题,可把JVM的DNS缓存反射出来添加DNS解析
public static void addJVMDNSCache() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Class clazz = java.net.InetAddress.class;
final Field cacheField = clazz.getDeclaredField("addressCache");
cacheField.setAccessible(true);
final Object o = cacheField.get(clazz);
Class clazz2 = o.getClass();
final Field cacheMapField = clazz2.getDeclaredField("cache");
cacheMapField.setAccessible(true);
final Map cacheMap = (Map) cacheMapField.get(o);
String ips[] = {"127.0.0.1"};
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
Object entry = newCacheEntry("localhost", ips, InetAddressCachePolicy.FOREVER);
synchronized (o) {
//cacheMap.clear();
cacheMap.put("localhost", entry);
}
} catch (Throwable te) {
throw new RuntimeException(te);
}
return null;
}
});
}
static Object newCacheEntry(String host, String[] ips, long expiration)
throws UnknownHostException, ClassNotFoundException, NoSuchMethodException,
IllegalAccessException, InvocationTargetException, InstantiationException {
String className = "java.net.InetAddress$CacheEntry";
Class<?> clazz = Class.forName(className);
// InetAddress.CacheEntry has only a constructor:
// - for jdk 6, constructor signature is CacheEntry(Object address, long expiration)
// - for jdk 7+, constructor signature is CacheEntry(InetAddress[] addresses, long expiration)
// code in jdk 6:
// http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b27/java/net/InetAddress.java#InetAddress.CacheEntry
// code in jdk 7:
// http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/net/InetAddress.java#InetAddress.CacheEntry
// code in jdk 8:
// http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/net/InetAddress.java#InetAddress.CacheEntry
Constructor<?> constructor = clazz.getDeclaredConstructors()[0];
constructor.setAccessible(true);
return constructor.newInstance(toInetAddressArray(host, ips), expiration);
}
static InetAddress[] toInetAddressArray(String host, String[] ips) throws UnknownHostException {
InetAddress[] addresses = new InetAddress[ips.length];
for (int i = 0; i < addresses.length; i++) {
addresses[i] = InetAddress.getByAddress(host, IpParserUtil.ip2ByteArray(ips[i]));
}
return addresses;
}