tornado解决高并发的初步认识牵扯出的一些问题
#!/bin/env python
# -*- coding:utf-8 -*-
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web import tornado.gen
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
import time
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int) class SleepHandler(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(2) @tornado.web.asynchronous
@tornado.gen.coroutine
def get(self):
# 假如你执行的异步会返回值被继续调用可以这样(只是为了演示),否则直接yield就行
res = yield self.sleep()
self.write("when i sleep %s s" % res)
self.finish() @run_on_executor
def sleep(self):
time.sleep(5)
return 5 class JustNowHandler(tornado.web.RequestHandler):
def get(self):
self.write("i hope just now see you") if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(handlers=[
(r"/sleep", SleepHandler), (r"/justnow", JustNowHandler)])
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
上面的代码示例转载自:https://blog.csdn.net/qq_28893679/article/details/69437496
本来通过线程池我觉得就可以实现高并发了,但是这位道友的@tornado.gen.coroutine这个装饰器,让我重新认识了协程,之前我一直以为协程是用来在单线程中解决io多路服用的,其实我还忽略了一个重要的地方,就是协程会主动让出CPU资源,这点我居然会遗忘,哎,天杀的,所以协程还有个重要的作用就是主动让出CPU资源。
@tornado.web.asynchronous的源码和自己瞎胡分析
@asynchronous源码:
def asynchronous(method):
"""Wrap request handler methods with this if they are asynchronous. This decorator is for callback-style asynchronous methods; for
coroutines, use the ``@gen.coroutine`` decorator without
``@asynchronous``. (It is legal for legacy reasons to use the two
decorators together provided ``@asynchronous`` is first, but
``@asynchronous`` will be ignored in this case) This decorator should only be applied to the :ref:`HTTP verb
methods <verbs>`; its behavior is undefined for any other method.
This decorator does not *make* a method asynchronous; it tells
the framework that the method *is* asynchronous. For this decorator
to be useful the method must (at least sometimes) do something
asynchronous. If this decorator is given, the response is not finished when the
method returns. It is up to the request handler to call
`self.finish() <RequestHandler.finish>` to finish the HTTP
request. Without this decorator, the request is automatically
finished when the ``get()`` or ``post()`` method returns. Example: .. testcode:: class MyRequestHandler(RequestHandler):
@asynchronous
def get(self):
http = httpclient.AsyncHTTPClient()
http.fetch("http://friendfeed.com/", self._on_download) def _on_download(self, response):
self.write("Downloaded!")
self.finish() .. testoutput::
:hide: .. versionchanged:: 3.1
The ability to use ``@gen.coroutine`` without ``@asynchronous``. .. versionchanged:: 4.3 Returning anything but ``None`` or a
yieldable object from a method decorated with ``@asynchronous``
is an error. Such return values were previously ignored silently.
"""
# Delay the IOLoop import because it's not available on app engine.
from tornado.ioloop import IOLoop @functools.wraps(method)
def wrapper(self, *args, **kwargs):
self._auto_finish = False
with stack_context.ExceptionStackContext(
self._stack_context_handle_exception):
result = method(self, *args, **kwargs)
if result is not None:
result = gen.convert_yielded(result) # If @asynchronous is used with @gen.coroutine, (but
# not @gen.engine), we can automatically finish the
# request when the future resolves. Additionally,
# the Future will swallow any exceptions so we need
# to throw them back out to the stack context to finish
# the request.
def future_complete(f):
f.result()
if not self._finished:
self.finish()
IOLoop.current().add_future(result, future_complete)
# Once we have done this, hide the Future from our
# caller (i.e. RequestHandler._when_complete), which
# would otherwise set up its own callback and
# exception handler (resulting in exceptions being
# logged twice).
return None
return result
return wrapper 蹩脚的翻译:
def asynchronous(method):
如果处理请求的方法是异步的,就用此方法来包装它(它代指get,post等方法)
这个装饰器用于回调类型的异步方法;对于协程,请用"@gen.coroutine"装饰器而不是"@asynchronous".(如果要同时合法的使用这两个装饰器,前提是"@asynchronous"要放在第一个也就是最外面,但在这种情况下"@asynchronous"将被忽略)
这个装饰器应该只能被应用到:ref:'HTTP 动态方法(get...)';它的行为对任何其它的方法都是未定义的.这个装饰器不制作异步方法;它告诉框架这个方法是异步的.对于这个装饰器包装的方法一定(至少一段时间)要做一些异步的事情.
如果给出了这个装饰器,被包装的方法已经return的时候响应还没有完成.完不完成取决于处理请求的方法去调用"self.finish()<RequestHandler.finish>"去结束这次HTTP请求.没有这个装饰器,请求会在"get()"或"post()"方法return的时候结束.例如: .. 测试代码:: class MyRequestHandler(RequestHandler):
@asynchronous
def get(self):
http = httpclient.AsyncHTTPClient()
http.fetch("http://friendfeed.com/", self._on_download) def _on_download(self, response):
self.write("Downloaded!")
self.finish() .. 测试输出::
:隐藏: .. 版本改变:3.1
能用"@gen.coroutine"实现就不用"@asynchronous" .. 版本改变:4.3 在被该装饰器包装的方法中返回"None"或者一个yieldable对象是一个错误.这种返回值在之前是默认忽略的.
# 延迟IOLoop导入因为它不能在app引擎上用
from tornado.ioloop import IOLoop @functools.wraps(method)
def wrapper(self,*args,**kwargs):
self._auto_finish = False
with stack_context.ExceptionStackContext(
self._stack_context_handle_exception):
result = method(self,*args,**kwargs)
if result is not None:
result = gen.convert_yielded(result) #如果 @asynchronous 是和@gen.coroutine(但不是@gen.engine)一起用的,我们
#能自动完成请求当future对象resolves时(我理解处于解决状态).此外,future对象
#将吞下所有异常,因此我们需要让他们退出堆栈上下文去完成请求.
def future_complete(f):
f.result()
if not self._finished:
self.finish()
IOLoop.current().add_future(result,future_complete)
#一旦我们完成了这一步,隐藏来自调用者的Future
#(即RequestHandler._when_complete),
#否则它会设置自己的回调和异常处理程序(导致异常被记录两次).
return None
return result
return wrapper
随后我又开始看了@gen.conroutine然后在源码里发现了一个神奇的模块types模块,大开这个模块后发现了各种类型的定义,然后我又莫名奇妙的想到了数据结构和数据类型,接下来就一发不可收拾了,简明python教程中说,数据结构是一种结构,能够将一些数据聚合在一起,也就是用来存储一系列相关数据的集合。python内置的数据结构有四种列表,集合,字典,元组。然后我又想起python的数据类型整形,字符串,列表,字典,集合,元组。到这里我开始犯糊涂了,怎么回事,数据结构也可以是数据类型么,活着数据类型也可以同时是数据结构么。查阅了很多资料(就是自己想了半天)后我总结除了自己的理解:
数据结构=数据+组合方式,就是把好多数据多放在一起了,对吧
数据类型=数据+处理方式,就是把原生数据(0101)加工处理了一下,变成了现有的数据
不要打我。。。
tornado解决高并发的初步认识牵扯出的一些问题的更多相关文章
- asp.net解决高并发的方案.
asp.net解决高并发的方案. Posted on 2012-11-27 22:31 75077027 阅读(3964) 评论(1) 编辑 收藏 最近几天一直在读代震军的博客,他是 Discuz!N ...
- Nginx和Tengine解决高并发和高可用,而非推荐Apache
什么是Nginx 什么是Tengine 看看国内大公司在用Nginx和Tengine吗? 步骤一:进入 https://www.taobao.com/,按F12.可看到 有很多APP对淘宝进行请求. ...
- 每一个程序员都应该知道的高并发处理技巧、创业公司如何解决高并发问题、互联网高并发问题解决思路、caoz大神多年经验总结分享
本文来源于caoz梦呓公众号高并发专辑,以图形化.松耦合的方式,对互联网高并发问题做了详细解读与分析,"技术在短期内被高估,而在长期中又被低估",而不同的场景和人员成本又导致了巨头 ...
- 用CAS方案解决高并发一致性问题
详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt395 缘起:在高并发的分布式环境下,对于数据的查询与修改容易引发一致性问题, ...
- 使用数据库乐观锁解决高并发秒杀问题,以及如何模拟高并发的场景,CyclicBarrier和CountDownLatch类的用法
数据库:mysql 数据库的乐观锁:一般通过数据表加version来实现,相对于悲观锁的话,更能省数据库性能,废话不多说,直接看代码 第一步: 建立数据库表: CREATE TABLE `skill_ ...
- 高并发场景系列(一) 利用redis实现分布式事务锁,解决高并发环境下减库存
原文:http://blog.csdn.net/heyewu4107/article/details/71009712 高并发场景系列(一) 利用redis实现分布式事务锁,解决高并发环境下减库存 问 ...
- 转发:php解决高并发
php解决高并发(转发:https://www.cnblogs.com/walblog/articles/8476579.html) 我们通常衡量一个Web系统的吞吐率的指标是QPS(Query Pe ...
- asp.net怎样解决高并发问题
队列+多线程+couchbase缓存 ,解决高并发问题. using System; using System.Collections.Generic; using System.Linq; usin ...
- PHP利用Mysql锁解决高并发
前面写过利用文件锁来处理高并发的问题的,现在我们说另外一个处理方式,利用Mysql的锁来解决高并发的问题 先看没有利用事务的时候并发的后果 创建库存管理表 CREATE TABLE `storage` ...
随机推荐
- Java后台模拟发送http的get和post请求,并测试
个人学习使用:谨慎参考 1 Client类 import com.thoughtworks.gauge.Step; import com.thoughtworks.gauge.Table; impor ...
- nodejs文件操作模块FS(File System)常用函数简明总结(转)
件系统操作相关的函数挺多的.首先可以分为两大类. 一类是异步+回调的. 一类是同步的. 在这里只对异步的进行整理,同步的只需要在函数名称后面加上Sync即可 1. 首先是一类最常规的读写函数,函数名称 ...
- 学习资料分享(Java第一行代码视频)<susmote.com>
17年买了一本书,第一行代码(JAVA),李兴华编写的. 一开始我是按照书本一页一页的啃,一个点一个点的去学,虽然当时学的有些枯燥,但里面的知识点大部分还是弄的懂,只是一次偶然,因为有点质疑书上写的( ...
- JAVA字符串缓存器全部方法功能及其作用
不知道干嘛的 serialVersionUID 构造一个没有字符的字符串缓冲区,初始容量为16个字符. StringBuffer() 构造一个没有字符的字符串缓冲区和指定的初始容量. StringBu ...
- 设计模式之 外观模式详解(Service第三者插足,让action与dao分手)
作者:zuoxiaolong8810(左潇龙),转载请注明出处,特别说明:本博文来自博主原博客,为保证新博客中博文的完整性,特复制到此留存,如需转载请注明新博客地址即可. 各位好,LZ今天给各位分享一 ...
- Java基础学习笔记十 Java基础语法之final、static、匿名对象、内部类
final关键字 继承的出现提高了代码的复用性,并方便开发.但随之也有问题,有些类在描述完之后,不想被继承,或者有些类中的部分方法功能是固定的,不想让子类重写.可是当子类继承了这些特殊类之后,就可以对 ...
- 通过运行一个tomcat容器来记录下初学docker常用的几个命令---容器篇
1.查看容器列表 显示正在运行的容器: [root@localhost HMK]# docker ps 显示所有容器,包括未运行的: [root@localhost HMK]# docker ps - ...
- [W班]第二次结对作业成绩评价
作业地址: https://edu.cnblogs.com/campus/fzu/FZUSoftwareEngineering1715W/homework/1016 作业要求: 1.代码具有规范性. ...
- c语言一,二数组
一.PTA实验作业 题目1:7-4 简化的插入排序 1. 本题PTA提交列表 2. 设计思路 1.定义整形变量N,temp,i. 2.输入N 3.通过for(i=1;i<=N;i++)的循环语句 ...
- Beta Scrum Day 3
听说