Python中使用Threads和Queue给tornado添加客户端

来源:互联网 发布:mac 连接云服务器 编辑:程序博客网 时间:2024/05/20 05:58

Python中使用Threads和Queue给tornado添加客户端


1 Python中使用Threads和Queue给tornado添加客户端

在使用tornado实现web服务器时,遇到需要使用客户端反向发送POST请求。在Handler中直接使用tornado客户端发送请求,服务端性能会受到影响,如果使用异步客户端(AsyncHTTPClient)会有所提高,异步客户端是短连接的,同样不符合需求。于是想到了使用多线程,比较好的解决方式是在Handler中把请求数据放到共享数据段,客户端的发送线程读取共享数据并发送。查了multiprocessing和threading,发现直接使用threading.Thread和Queue最简单。

from threading import Threadfrom Queue import Queueif __name__ == "__main__":    q = Queue()    def client_handler(q, i):        client = httpclient.HTTPClient()        print("client%d handler started "%(i))        while True:            msg = q.get()            try:                resp = client.fetch(settings.get('mms_url', ''), method='POST', user_agent='MMSC Simulator', body=msg, headers={'soapAction': '""', 'x-mmsc-msg-from': 'mm7', 'Mime-Version': '1.0', 'Content-Type': 'text/xml; charset=utf-8', 'Content-Transfer-Encoding':'8bit', 'Connection': 'Keep-alive'})                if resp.error:                    print("Error", resp.error)            except:                print("Error Resp: ")        print("client%d handler stopped %d %d"%(i, success, failed))    application = tornado.web.Application([        (settings.get('mmsc_path', r'/mms/'), MainHandler, dict(queue = q)),        ( r'/was/', WasHandler, dict(queue = q)),    ], **settings)    for i in range(10):        t = Thread(target=client_handler, args = (q,i))        t.daemon = True        t.start()    application.listen(settings.get('mmsc_port', 8000), address="0.0.0.0")    tornado.ioloop.IOLoop.instance().start()    q.join()

发现自己开辟线程中不能使用AsyncHTTPClient,找了下tornado的代码,没找到具体原因,有时间在深入了解下torando。

Created: 2014-05-05 Mon 19:39

Emacs 24.3.90.1 (Org mode 8.2.5c)

Validate

0 0