【发布时间】:2011-09-29 16:14:04
【问题描述】:
我正在处理两个内部 Web 服务器,一个在 Ubuntu Server 10.04 上运行 Apache2,另一个在 Windows Server 2008 上运行 IIS。当我从一个清除缓存的 Web 浏览器中访问任一根 URL 时,调用服务器通过IP地址,两者都弹出没有延迟。我也看到在任一服务器上浏览网站都没有延迟。但是,当我在 Python 中使用 urllib2 调用相同的地址时,对 Apache2 服务器的每个请求都会延迟 4.5 到 5 秒。 IIS 服务器在不到 0.02 秒内响应。
这是我为验证问题而运行的脚本。我设置了 User-Agent 以防万一,但它似乎没有:
import urllib2
from time import time
apache_server = 'http://192.168.1.101/'
iis_server = 'http://192.168.1.102/'
headers = {'User-Agent' : "Mozilla/5.0 (X11; U; Linux i586; de; rv:5.0) Gecko/20100101 Firefox/5.0",}
print('Contacting Apache2 server...')
request = urllib2.Request(url=apache_server, headers=headers)
start = time()
response = urllib2.urlopen(request).read()
elapsed = time() - start
print('Elapsed time: {0}'.format(elapsed))
print('Contacting IIS server...')
request = urllib2.Request(url=iis_server, headers=headers)
start = time()
response = urllib2.urlopen(request).read()
elapsed = time() - start
print('Elapsed time: {0}'.format(elapsed))
结果:
>python urltest.py
Contacting Apache2 server...
Elapsed time: 4.55500006676
Contacting IIS server...
Elapsed time: 0.0159997940063
浏览器请求和我的 urllib2 请求之间有什么区别可以解释这种延迟?
我看到过由反向 DNS 查找引起的 SSH 类似问题,但我的 Apache2 配置中有 HostnameLookups Off。我不知道是否还有其他可能触发查找。
更新:我跟踪了与 Wireshark 的交流,发现三个失败的 NBNS 查询从我的机器发送到 Apache2 服务器,然后才最终开始交谈。这占了损失的时间。我尝试在 hosts 中为 Web 服务器添加一个条目,从而消除了延迟。
我没有将此作为答案添加,因为我仍然不知道为什么会发生查找尝试,或者为什么我没有从网络浏览器中看到相同的行为。无论我犯了什么错误,我都有一个解决方法。
【问题讨论】: