java - 在 java.net.URL 类中为 DNS 查找提供自定义实现

标签 java caching dns

我想知道是否可以为 java.net.URL 上的 DNS 查找提供自定义实现 - 我的托管服务提供商的 DNS 在一天中的某些时间变得不稳定,然后 DNS 查找失败几分钟,但如果我手动配置我的主机文件中的相关域,它们工作正常,所以我想做的是在软件级别有某种 DNS 缓存,如果 DNS 查找成功,更新缓存,如果失败,回退到缓存的 IP 地址并在该 IP 地址上打开 URLConnection。

这是我的 URL 连接实现:

    URL endpoint = new URL(null, url, new URLStreamHandler() {
        @Override
        protected URLConnection openConnection(URL url)
                throws IOException {
            URL target = new URL(url.toString());
            URLConnection connection = target.openConnection();
            // Connection settings
            connection.setConnectTimeout(connectionTimeout);
            connection.setReadTimeout(readTimeout);
            return (connection);
        }
    });

我在 Oracle 上查看代理,但看不到任何在软件级别进行自定义 DNS 查找的直接方法。

限制:

1:它需要在 Java6 中工作(可能是 Java7,但客户端不会很快切换到 Java8)

2: 无法添加 JVM args

3:我不拥有这些端点,因此用 IP 地址替换主机名不是解决方案,因为负载均衡器将根据您来自主机名还是 IP 地址来提供不同的内容/API。例如:mail.google.com 解析为 216.58.223.37,转到该 IP 地址将提供 google.com 内容而不是 mail.google.com 内容,因为这两个服务都位于使用单个 IP 地址的同一个负载均衡器后面.

4:我不知道我需要缓存多少 URL 的 DNS 解析,但我知道它不会超过 1000。理想的解决方案是将 DNS 解析放在静态 HashMap 中,如果任何DNS解析成功,则更新hashmap,如果失败,则使用hashmap中的DNS解析。

5:如果有本地 Java 解决方案,我更愿意使用它而不是使用 JNI - Understanding host name resolution and DNS behavior in Java

最佳答案

您可以创建自定义方法来检查主机是否解析为 IP。在打开连接之前,如果主机未解析,则进行查找并直接使用 IP 来构建 URL:

在类里面:

private Map<String,InetAddress> cacheMap = new HashMap<String,InetAddress>();

....然后是构建 URL 的几种方法:

private URL buildUrl (String host) throws MalformedURLException {
    InetAddress ia = resolveHostToIp(host);
    URL url = null;

    if (ia != null) {
        url = new URL(ia.getHostAddress());
    } else {
        // Does not resolve and is not in cache....dunno
    }
    return url;
}


 private InetAddress resolveHostToIp(String host) {
    InetAddress ia = null;
    try {
        ia = InetAddress.getByName(host);
        // Update your cache
        cacheMap.put(host, ia);
    } catch (UnknownHostException uhe) {
        System.out.println("\"" + host + "\" does not resolve to an IP! Looking for it in the cacheMap....");
        // Head off to your cache and return the InetAddress from there.....
        ia = cacheMap.get(host);
    }
    return ia;
}

关于java - 在 java.net.URL 类中为 DNS 查找提供自定义实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28361164/

相关文章:

dns - 使用 DNS 重定向到另一个带有路径的 URL

azure - Azure 为记录提供的 IP 地址出现 404 错误

java - 将 GreenDao 与 Retrofit 集成

java - 访问 Object[] 数组成员的方法

asp.net - OutputCache 指令在 Asp.Net 中不起作用

ios - fileManager.createFileAtPath 在单元测试期间失败

java.util.Map 和 google 缓存实现(com.google.common.cache.Cache)的区别

Java try catch 错误

caching - 反向代理 HTTP 请求的后处理? (如 Akamai 的 ESI)

python - python 脚本的备用主机/IP