HTTPRequest AsyncHTTPClient.configure HTTP 599: Timeout in request queue 异常处理html
tornado的AsyncHTTPClient做为爬虫客户端使用起来很方便, 可是为了应对网站的IP访问限制,这个时候就须要使用IP代理机制了, AsyncHTTPClient通过简单的配置就能够使用HTTP代理来进行http访问了, 正好结合tornado的异步机制,就能够同时开多个链接去访问不一样的内容,提升爬取速度。python
不过在windows上因为curl库的关系,我没有跑起来,本文的代码能够跑在linux下面。linux
import tornado.ioloop from tornado.httpclient import HTTPRequest, AsyncHTTPClient @tornado.gen.coroutine def send_requ(): http_requ = HTTPRequest( url='http://www.baidu.com', method='GET', proxy_host = 'a.b.c.d', # 配置HTTP代理的ip地址 proxy_port = 1234, # 设置HTTP代理的端口 ) http_resp = yield AsyncHTTPClient().fetch(http_requ) #处理回复消息。。。 if __name__ == "__main__": # 配置 AsyncHTTPClient AsyncHTTPClient.configure( "tornado.curl_httpclient.CurlAsyncHTTPClient", # 必须配置这个否则没法使用代理 max_clients=600 # 客户端池数量配置设大一点 ) tornado.ioloop.IOLoop.run_sync(send_requ)
上面的那段代码在程序启动时会调用AsyncHTTPClient.configure将最大的可用客户端数量设置为600了,到达600以后全部待发送的请求都会进入排队机制,可是该队列里面的请求有个排队时间,若是超时tornado将会丢弃这个请求并给调用方抛出一个异常。web
tornado.httpclient.HTTPError: HTTP 599: Timeout in request queue
下面的代码能够让AsyncHTTPClient排队的请求不会超时windows
from tornado.httpclient import AsyncHTTPClient from tornado.log import gen_log from tornado.simple_httpclient import SimpleAsyncHTTPClient class NoQueueTimeoutHTTPClient(SimpleAsyncHTTPClient): def fetch_impl(self, request, callback): key = object() self.queue.append((key, request, callback)) self.waiting[key] = (request, callback, None) self._process_queue() if self.queue: gen_log.debug("max_clients limit reached, request queued. %d active, %d queued requests." % ( len(self.active), len(self.queue))) AsyncHTTPClient.configure(NoQueueTimeoutHTTPClient, max_clients=20)