HttpExchange.getRemoteAddress()需要很长时间

时间:2019-04-23 11:28:51

标签: java http

我正在创建在Java HttpServer类上运行的服务器,一切正常,但是我注意到对exchange.getRemoteAddress().getAddress().getCanonicalHostName()的调用大约需要4000毫秒,但是即使删除getRemoteAddress(),读取请求正文也很快。有谁知道为什么HttpExchange.getRemoteAddress()需要这么长时间? 从服务器登录:

[pool-1-thread-1 | 13:25:54] Received request from 192.168.0.104 / Obtaining remote address took 4538 ms
[pool-1-thread-1 | 13:25:54] Downloading request body from 192.168.0.104 took 0 ms
[pool-1-thread-1 | 13:25:54] Generating response body from 192.168.0.104 took 6 ms
[pool-1-thread-1 | 13:25:54] Processing lock request from 192.168.0.104

exchange.getRemoteAddress().getAddress().getCanonicalHostName()替换为硬编码字符串(“测试”)时记录:

[pool-1-thread-1 | 13:28:00] Received request from test / Obtaining remote address took 0 ms
[pool-1-thread-1 | 13:28:00] Downloading request body from test took 1 ms
[pool-1-thread-1 | 13:28:00] Generating response body from test took 7 ms
[pool-1-thread-1 | 13:28:00] Processing lock request from test

编辑: 我的失败,没有正确阅读getCanonicalHostName()文档。它清楚地说

  

获取此IP地址的标准域名。最大努力   方法,这意味着我们可能无法返回FQDN,具体取决于   基础系统配置。

替换为getHostAddress()

1 个答案:

答案 0 :(得分:1)

这是因为查找给定IP地址的主机名通常会涉及reverse DNS lookup,即网络查询(或一系列查询),这是一项昂贵的操作,并且比使用硬编码的字符串值要慢得多