dns解析优化
# DNS解析优化
# 背景
使用了cloudflare的proxy,在阿里云上请求到cf代理的域名上,经常出现dns解析失败,基本上是一次成功,下次失败. 而用dns查询工具可以看到,cf的ip基本都是那两个,在国内各省市,有的能解析成功,有的解析不成功.
于是,做一层内存缓存:
# okhttp实现
static Map<String, List<InetAddress>> dnsMap = new HashMap<>();
okHttpClient = new OkHttpClient.Builder()
.readTimeout(Duration.ofSeconds(50))
.writeTimeout(Duration.ofSeconds(50))
.connectTimeout(Duration.ofSeconds(50))
.dns(new Dns() {
@NotNull
@Override
public List<InetAddress> lookup(@NotNull String host) throws UnknownHostException {
try {
InetAddress[] allByName = InetAddress.getAllByName(host);
if(allByName != null && allByName.length >0){
List<InetAddress> addresses = new ArrayList<>();
for (InetAddress inetAddress : allByName) {
addresses.add(inetAddress);
}
dnsMap.put(host,addresses);
return addresses;
}
List<InetAddress> addresses = dnsMap.get(host);
if(addresses != null && !addresses.isEmpty()){
return addresses;
}else {
throw new UnknownHostException(" ---> can not resole host: "+host);
}
}catch (Throwable throwable){
List<InetAddress> addresses = dnsMap.get(host);
StaticLog.warn(throwable,"UnknownHostException then read cache : "+ host+"--->"+addresses);
if(addresses != null && !addresses.isEmpty()){
return addresses;
}else {
throw new UnknownHostException(" ---> can not resole host2: "+host);
}
}
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 效果
使用缓存后,看api日志, 再也没有出现UnknownHostException了.
编辑 (opens new window)
上次更新: 2023/05/09, 17:55:07