簡體   English   中英

在java.net.URL類中提供DNS查找的自定義實現

[英]Provide custom implementation for DNS lookup in java.net.URL class

我想知道是否有可能在java.net.URL上為DNS查找提供自定義實現 - 我的托管服務提供商的DNS在一天的某些時間變得不穩定,然后DNS查找失敗幾分鍾,但如果我手動配置相關域在我的hosts文件中,它們工作正常,所以我想做的是在軟件級別有一些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 - 了解Java中的主機名解析和DNS行為

您可以簡單地構建另一個URL:

URL target = new URL(
    url.getProtocol(),
    customDns.resolve(url.getHost()),
    url.getFile());

您可以使用您需要的任何策略實現customDns.resolve(String)

您可以創建自定義方法來檢查主機是否解析為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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM