我已经构建了一个用于 DNS 解析的小型辅助类:
public class DNSService {
private static Properties env;
private static final String CNAME_ATTRIB = "CNAME";
private static String[] CNAME_ATTRIBS = { CNAME_ATTRIB };
static {
env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
}
public static String getCNAME(String host) throws NamingException {
return getCNAME(new InitialDirContext(env), host);
}
private static String getCNAME(InitialDirContext idc, String host) throws NamingException {
String cname = host;
Attributes attrs = idc.getAttributes(host, CNAME_ATTRIBS);
Attribute attr = attrs.get(CNAME_ATTRIB);
if (attr != null) {
int count = attr.size();
if (count == 1) {
cname = getCNAME(idc, (String) attr.get(0));
} else {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++) {
sb.append("-> " + attr.get(i) + "\n");
}
throw new NamingException("Unexpected count while looking for CNAME of " + host + ". Expected 1. Got " + count + ".\n"
+ sb.toString());
}
}
return cname;
}
}
这个类被不同的线程使用。但是,此类产生的结果在两个线程调用之间略有不同。
例如,我在同一天得到这些结果:
<Date> <Hour> <Thread Name> <Host> <Canonical Name>
02/12/2012 09:51 thread-1 www.site.com www.site.com
02/12/2012 12:06 thread-2 www.site.com time.microsoft.akadns.net.
为什么我使用 time.microsoft.akadns.net.
获得最终的规范名称?
有时第二次调用可以获得多个规范名称,如下所示:
qq.com.edgesuite.net.
a1574.b.akamai.net.
为什么两次通话的结果如此不同?为什么每次调用都没有一个 CNAME?
最佳答案
也许主机使用 DNS 解析作为一种负载平衡?例如,查看来自亚马逊的官方文档:
http://aws.amazon.com/en/route53/faqs/
讨论 WRR 和 Elastic Load Balance 的地方。也许你的数据与一些负载平衡混合在一起,这些负载平衡根据负载考虑来解决你对不同后端的请求,这就是你得到不同答案的原因
关于java - 如何在 Java 中获取主机名的规范名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20394696/