猿问

tornado框架调用AsyncHTTPClient,出现阻塞并严重延迟的问题?

1,我有用tornado框架搭建了一个web服务对外提供访问,我们暂且叫他A服务,这个A服务实际上就是调用本机的另一个web服务(也是tornado搭建的)我们暂且叫它B服务,如果B服务返回不是200,就调用另一个web服务(也是tornado搭建的)我们暂且叫它C服务,都是本机localhost调用,我发现被调用的B,C服务都很快结束,不到1秒,而A服务这边做的时间计时,发现很慢,达到20秒,请各位帮我看看!

我用的python2.7,tornado3.2

2,以下是代码

@asynchronous
@gen.coroutine
def get(self):
    cost_array=[int(time.time()*1000)]
    result=yield self.callB(q,start_date)
    cost_array.append(int(time.time()*1000))
    if result["code"]!=200:
        result=yield self.callC(q,start_date)
        cost_array.append(int(time.time() * 1000))
        
    self.set_status(result["code"])
    self.write(result["response"])
    
   @gen.coroutine
def callB(self, q, start_date):
    result={
        "code":0,
        "response":{}
    }
    url="http://localhost:8200/*?q=%s&startdate=%s"%(q,start_date)
    request = HTTPRequest(url=url,\
                          method="GET", \
                          follow_redirects=False,\
                          request_timeout=3000)
    sever_response=yield gen.Task(AsyncHTTPClient().fetch,request)

    result["code"]=sever_response.code
    if sever_response.body:
        result["response"]=sever_response.body
    raise gen.Return(result)
    
@gen.coroutine
def callC(self, q, start_date):
    result={
        "code":0,
        "response":{}
    }
    url="http://localhost:8200/*?q=%s&startdate=%s"%(q,start_date)
    request = HTTPRequest(url=url,\
                          method="GET", \
                          follow_redirects=False,\
                          request_timeout=3000)
    sever_response=yield gen.Task(AsyncHTTPClient().fetch,request)

    result["code"]=sever_response.code
    if sever_response.body:
        result["response"]=sever_response.body
    raise gen.Return(result)
    

以上代码执行一段时间还行,过了一段时间后,cost_array数组里面记录的时间戳直接差距的秒数能达到20秒以上,然后服务也没办法对外提供访问了,但进程的cpu和内存占用很小!!访问都是超时了。只能重启服务

ITMISS
浏览 1463回答 4
4回答

MM们

将代码: url="http://localhost:8200/*?q=%s&startdate=%s"%(q,start_date) request = HTTPRequest(url=url,\ method="GET", \ follow_redirects=False,\ request_timeout=3000) sever_response=yield gen.Task(AsyncHTTPClient().fetch,request) 改为以下方式即可: sever_response=yield AsyncHTTPClient().fetch(url) 即可

qq_遁去的一_1

HTTPRequest 默认选项request_timeout 就是 20S,你超时时间单位搞错了吧

胡说叔叔

tornado有个坑人的参数,调用耗时的服务会被触发,max_clients表示ioloop中可以并发执行的httpclient数量
随时随地看视频慕课网APP

相关分类

Python
我要回答