#!/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解决高并发的初步认识牵扯出的一些问题的更多相关文章

  1. asp.net解决高并发的方案.

    asp.net解决高并发的方案. Posted on 2012-11-27 22:31 75077027 阅读(3964) 评论(1) 编辑 收藏 最近几天一直在读代震军的博客,他是 Discuz!N ...

  2. Nginx和Tengine解决高并发和高可用,而非推荐Apache

    什么是Nginx  什么是Tengine 看看国内大公司在用Nginx和Tengine吗? 步骤一:进入 https://www.taobao.com/,按F12.可看到 有很多APP对淘宝进行请求. ...

  3. 每一个程序员都应该知道的高并发处理技巧、创业公司如何解决高并发问题、互联网高并发问题解决思路、caoz大神多年经验总结分享

    本文来源于caoz梦呓公众号高并发专辑,以图形化.松耦合的方式,对互联网高并发问题做了详细解读与分析,"技术在短期内被高估,而在长期中又被低估",而不同的场景和人员成本又导致了巨头 ...

  4. 用CAS方案解决高并发一致性问题

    详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt395 缘起:在高并发的分布式环境下,对于数据的查询与修改容易引发一致性问题, ...

  5. 使用数据库乐观锁解决高并发秒杀问题,以及如何模拟高并发的场景,CyclicBarrier和CountDownLatch类的用法

    数据库:mysql 数据库的乐观锁:一般通过数据表加version来实现,相对于悲观锁的话,更能省数据库性能,废话不多说,直接看代码 第一步: 建立数据库表: CREATE TABLE `skill_ ...

  6. 高并发场景系列(一) 利用redis实现分布式事务锁,解决高并发环境下减库存

    原文:http://blog.csdn.net/heyewu4107/article/details/71009712 高并发场景系列(一) 利用redis实现分布式事务锁,解决高并发环境下减库存 问 ...

  7. 转发:php解决高并发

    php解决高并发(转发:https://www.cnblogs.com/walblog/articles/8476579.html) 我们通常衡量一个Web系统的吞吐率的指标是QPS(Query Pe ...

  8. asp.net怎样解决高并发问题

    队列+多线程+couchbase缓存 ,解决高并发问题. using System; using System.Collections.Generic; using System.Linq; usin ...

  9. PHP利用Mysql锁解决高并发

    前面写过利用文件锁来处理高并发的问题的,现在我们说另外一个处理方式,利用Mysql的锁来解决高并发的问题 先看没有利用事务的时候并发的后果 创建库存管理表 CREATE TABLE `storage` ...

随机推荐

  1. 使用Intellij IDEA生成JavaDoc

    以下是常用的注释标签,规范书写生成的文档中才能显示: @author 作者 @version 版本 @see 参考转向 @param 参数说明 @return 返回值说明 @exception 异常说 ...

  2. R语言-用户细分

    案例:通过使用R语言的聚类算法将用户进行合理的划分,找出对超市贡献度,光临度最高的优质客户,对后期的推广有更深远的影响 1.导入包 library(dplyr) library(reshape2) l ...

  3. FxCop卸载后依然生成文件夹的问题

    在 http://www.cnblogs.com/heroius/p/8270004.html 中,通过编辑csproj文件可以移除对旧版nuget独立程序的依赖. 实际上,通过编辑项目文件的方式可以 ...

  4. Android短信验证码倒计时

    有两种实现方法 1.第一种方式:Timer /** * Description:自定义Timer * <p> * Created by Mjj on 2016/12/4. */ publi ...

  5. oracle10g 基于linux6安装问题收集

    1.[oracle@rsyslogserver database]$ dbca -silent -responseFile /home/oracle/database/dbca.rsp No comm ...

  6. 【Django】 初步学习

    这个系列(或者成不了一个系列..)预计会全程参考Vamei様的Django系列,膜一发.说句题外话,其实更加崇拜像Vamei那样的能够玩转生活.各个领域都能取得不小成就的人. [Django] ■ 概 ...

  7. Algorithm --> 邮票连续组合问题

    邮票组合问题 有四种面值的邮票很多枚,面值分别为1,4,12,21,取五张,求取出这些邮票的最大连续组合值 代码: #include <stdio.h> #include <stri ...

  8. Oracle查询优化改写--------------------范围处理

    一.定位连续值的范围 二.查找同一组或分区中行之间的差

  9. codeforce round#466(div.2)C. Phone Numbers

    C. Phone Numbers time limit per test2 seconds memory limit per test256 megabytes inputstandard input ...

  10. Linux安装java环境教程

    前言: 本教程基于jdk 1.8,但是此教程适用于jdk1.7等版本. 教程正文: 1.1. 登录Oracle官网下载jdk1.8安装包(gz结尾) 这里可以用"wget + 下载地址&qu ...