我正在开发一个python 2.7脚本,必须在Fedora Commons存储库中检查20'000个对象中是否存在某些数据。 基本上这意味着向存储库(在Tomcat服务器上运行)发送20'000个HTTP请求到20'000个不同的URL。
我编写了一个完成这项工作的脚本,但是服务器系统管理员已经警告我打开了太多的网络连接,这会导致一些麻烦。
我的脚本使用到目前为止urllib2来发出HTTP请求。
response = urllib2.urlopen(url)
response_content = response.read()
实际上,此代码会为每个请求打开一个新的网络连接。
我曾尝试使用其他库来发出请求,但无法找到任何方法为所有请求重用相同的连接。下面的两个解决方案仍然会打开许多网络连接,即使它们的数量确实较低(实际上两个解决方案似乎都为100个HTTP请求打开了一个连接,在我的情况下仍然是大约200个连接)。
httplib的:
url = "http://localhost:8080/fedora/objects/test:1234?test="
url_infos = urlparse(url)
conn = httplib.HTTPConnection(url_infos.hostname + ":" + str(url_infos.port))
for x in range(0, 20000):
myurl = url + str(x)
conn.request("GET", myurl)
r = conn.getresponse()
response_content = r.read()
print x, "\t", myurl, "\t", r.status
请求:
url = "http://localhost:8080/fedora/objects/test:1234?test="
s = requests.Session()
for x in range(0, 20000):
myurl = url + str(x)
r = s.get(myurl)
response_content = r.content
print x, "\t", myurl, "\t", r.status_code
即使连接数要好得多,理想情况下我也想为所有请求使用一个或几个连接。这甚至可能吗?每个连接有100个请求与系统或服务器有关吗?顺便说一下,我也尝试将请求指向Apache服务器,结果是一样的。
答案 0 :(得分:3)
这两个解决方案共享了一些像Lukasa这样的代码的事实,以及每当查询Apache或Tomcat时两个结果都相同的事实 让我首先想到它与Python代码有关。但实际上它与服务器配置有关。
技巧是Apache和Tomcat共享一个设置,指示在同一TCP连接中可以进行多少HTTP请求。两者的默认值均为100。
Tomcat的:
maxKeepAliveRequests:
The maximum number of HTTP requests which can be pipelined until the connection is closed by the server.
If not specified, this attribute is set to 100.
请参阅http://tomcat.apache.org/tomcat-7.0-doc/config/http.html#Standard_Implementation
的Apache:
MaxKeepAliveRequests:
The MaxKeepAliveRequests directive limits the number of requests allowed per connection when KeepAlive is on
Default: MaxKeepAliveRequests 100
请参阅http://httpd.apache.org/docs/2.2/en/mod/core.html#maxkeepaliverequests
通过修改这些值,只能创建很少的连接