最新消息:

Python-aiohttp百万并发(上)

http admin 14367浏览 0评论

本文将测试python aiohttp的极限,同时测试其性能表现,以分钟发起请求数作为指标。大家都知道,当应用到网络操作时,异步的代码表现更优秀,但是验证这个事情,同时搞明白异步到底有多大的优势以及为什么会有这样的优势仍然是一件有趣的事情。为了验证,我将发起1000000请求,用aiohttp客户端。aiohttp每分钟能够发起多少请求?你能预料到哪些异常情况以及崩溃会发生,当你用比较粗糙的脚本去发起如此大量的请求?面对如此大量的请求,哪些主要的陷阱是你需要去思考的?

初识 asyncio/aiohttp

异步编程并不简单。相比平常的同步编程,你需要付出更多的努力在使用回调函数,以事件以及事件处理器的模式进行思考。同时也是因为asyncio相对较新,相关的教程以及博客还很少的缘故。官方文档非常简陋,只有最基本的范例。在我写本文的时候,Stack Overflow上面,只有410个与asyncio相关的话题(相比之下,twisted相关的有2585)。有个别关于asyncio的不错的博客以及文章,比如这个这个这个,或者还有这个以及这个

简单起见,我们先从基础开始 —— 简单HTTP hello world —— 发起GET请求,同时获取一个单独的HTTP响应。

同步模式,你这么做:

import requests 
def hello()    
     return requests.get("http://httpbin.org/get")     

print(hello())

接着我们使用aiohttp:

#!/usr/local/bin/python3.5 
import asyncio 
from aiohttp import ClientSession 

async def hello():     
    async with ClientSession() as session:         
        async with session.get("http://httpbin.org/headers") as response:                
            response = await response.read()                         
            print(response) 
  
loop = asyncio.get_event_loop() 
loop.run_until_complete(hello())

好吧,看上去仅仅一个简单的任务,我写了很多的代码……那里有“async def”、“async with”、“await”—— 看上去让人迷惑,让我们尝试弄懂它们。

你使用async以及await关键字将函数异步化。在hello()中实际上有两个异步操作:首先异步获取相应,然后异步读取响应的内容。

Aiohttp推荐使用ClientSession作为主要的接口发起请求。ClientSession允许在多个请求之间保存cookie以及相关对象信息。Session(会话)在使用完毕之后需要关闭,关闭Session是另一个异步操作,所以每次你都需要使用async with关键字。

一旦你建立了客户端session,你可以用它发起请求。这里是又一个异步操作的开始。上下文管理器的with语句可以保证在处理session的时候,总是能正确的关闭它。

要让你的程序正常的跑起来,你需要将他们加入事件循环中。所以你需要创建一个asyncio loop的实例, 然后将任务加入其中。

看起来有些困难,但是只要你花点时间进行思考与理解,就会有所体会,其实并没有那么复杂。

访问多个链接

现在我们来做些更有意思的事情,顺序访问多个链接。

同步方式如下:

for url in urls:     
    print(requests.get(url).text)

很简单。不过异步方式却没有这么容易。所以任何时候你都需要思考,你的处境是否有必要用到异步。如果你的app在同步模式工作的很好,也许你并不需要将之迁移到异步方式。如果你确实需要异步方式,这里会给你一些启示。我们的异步函数hello()还是保持原样,不过我们需要将之包装在asyncio的Future对象中,然后将Future对象列表作为任务传递给事件循环。

loop = asyncio.get_event_loop() 
tasks = [] # I'm using test server localhost, but you can use any url 
url = "http://localhost:8080/{}" 
for i in range(5):     
    task = asyncio.ensure_future(hello(url.format(i)))     
    tasks.append(task) 

loop.run_until_complete(asyncio.wait(tasks))

现在假设我们想获取所有的响应,并将他们保存在同一个列表中。目前,我们没有保存响应内容,仅仅只是打印了他们。让我们返回他们,将之存储在一个列表当中,最后再打印出来。

为了达到这个目的,我们需要修改一下代码:

#!/usr/local/bin/python3.5 
import asyncio 
from aiohttp import ClientSession 

async def fetch(url):      
   async with ClientSession() as session:           
      async with session.get(url) as response:             
          return await response.read()             
          
async def run(loop,  r):     
   url = "http://localhost:8080/{}"         
   tasks = []         
   for i in range(r):             
       task = asyncio.ensure_future(fetch(url.format(i)))                 
       tasks.append(task)         
       responses = await asyncio.gather(*tasks)         
       # you now have all response bodies in this variable         
       print(responses)     
       
def print_responses(result):       
    print(result)     
    
loop = asyncio.get_event_loop() 
future = asyncio.ensure_future(run(loop, 4)) 
loop.run_until_complete(future)

注意asyncio.gather()的用法,它搜集所有的Future对象,然后等待他们返回。

常见错误

现在我们来模拟真实场景,去调试一些错误,作为演示范例。

看看这个:

# WARNING! BROKEN CODE DO NOT COPY PASTE 
async def fetch(url):      
   async with ClientSession() as session:           
      async with session.get(url) as response:                     
          return response.read()

如果你对aiohttp或者asyncio不够了解,即使你很熟悉Python,这段代码也不好debug。

上面的代码产生如下输出:

pawel@pawel-VPCEH390X ~/p/l/benchmarker> ./bench.py  
[<generator object ClientResponse.read at 0x7fa68d465728>,
 <generator object ClientResponse.read at 0x7fa68cdd9468>,
 <generator object ClientResponse.read at 0x7fa68d4656d0>,
 <generator object ClientResponse.read at 0x7fa68cdd9af0>]

发生了什么?你期待获得响应对象,但是你得到的是一组生成器。怎么会这样?

我之前提到过,response.read()是一个异步操作,这意味着它不会立即返回结果,仅仅返回生成器。这些生成器需要被调用跟运行,但是这并不是默认行为。在Python34中加入的yield from以及Python35中加入的await便是为此而生。它们将迭代这些生成器。以上代码只需要在response.read()前加上await关键字即可修复。如下:

    # async operation must be preceded by await          
    return await response.read() 
    # NOT: return response.read()

我们看看另一个例子。

# WARNING! BROKEN CODE DO NOT COPY PASTE 
async def run(loop,  r):       
   url = "http://localhost:8080/{}"         
   tasks = []         
   for i in range(r):             
       task = asyncio.ensure_future(fetch(url.format(i)))                 
       tasks.append(task)         
       responses = asyncio.gather(*tasks)         
       print(responses)

输出结果如下:

 

pawel@pawel-VPCEH390X ~/p/l/benchmarker> ./bench.py  
<_GatheringFuture pending> 
Task was destroyed but it is pending! 
task: <Task pending coro=<fetch() running at ./bench.py:7> 
        wait_for=<Future pending cb=[Task._wakeup()]> 
        cb=[gather.<locals>._done_callback(0)() 
        at /usr/local/lib/python3.5/asyncio/tasks.py:602]> 
Task was destroyed but it is pending! 
task: <Task pending coro=<fetch() running at ./bench.py:7> 
  wait_for=<Future pending cb=[Task._wakeup()]> 
  cb=[gather.<locals>._done_callback(1)() 
  at /usr/local/lib/python3.5/asyncio/tasks.py:602]> 
Task was destroyed but it is pending! 
task: <Task pending coro=<fetch() running at ./bench.py:7> 
  wait_for=<Future pending cb=[Task._wakeup()]> 
  cb=[gather.<locals>._done_callback(2)() 
  at /usr/local/lib/python3.5/asyncio/tasks.py:602]> 
Task was destroyed but it is pending! 
task: <Task pending coro=<fetch() running at ./bench.py:7>
  wait_for=<Future pending cb=[Task._wakeup()]> 
  cb=[gather.<locals>._done_callback(3)() 
  at /usr/local/lib/python3.5/asyncio/tasks.py:602]>

发生了什么?查看本地日志,你会发现没有任何请求到达服务器,实际上没有任何请求发生。打印信息首先打印<_Gathering pending>对象,然后警告等待的任务被销毁。又一次的,你忘记了await。

修改

    responses = asyncio.gather(*tasks)

    responses = await asyncio.gather(*tasks)

即可解决问题。

经验:任何时候,你在等待什么的时候,记得使用await。

 

Python-aiohttp百万并发(下)

转载请注明:爱开源 » Python-aiohttp百万并发(上)

您必须 登录 才能发表评论!