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
- Python中使用Threads和Queue给tornado添加客户端
- 给tornado添加dbutils支持
- 给tornado添加dbutils支持
- Python Tornado 使用经验
- python tornado模板使用
- python 中的 csrf(xsrf: 在 tornado 中) 和 cors
- [零基础学python]使用tornado表单和模板
- [零基础学python]使用tornado表单和模板
- [零基础学python]使用tornado表单和模板
- Python中的线程使用 和 queue
- 【tmp】python Queue和Thread结合使用
- 在python中实现生产者和消费者的例子(二):使用multiprocessing和queue
- ASP.NET(C#)中给控件添加客户端js事件
- java 中Queue和ListedList的使用
- acm中Stack和Queue使用demo
- tornado和sqlalchemy结合使用
- python中mulprocessing.Queue
- Python Queue的使用
- java判断文件的编码
- 数据结构链表自测题——2014-5-5
- http详解
- Trie树基本概念和训练指南
- B. Prison Transfer
- Python中使用Threads和Queue给tornado添加客户端
- UVaOJ 694 - The Collatz Sequence
- Mysql导入数据库及表结构和数据在cmd中
- 为什么以太网最小帧长为64字节
- C++学习总结——类和对象、构造函数和拷贝构造函数
- 程序员为什么要加班
- Skynet协同模型
- 关于c语言链表的操作
- javascript笔记-----------js闭包