2017-02-02 88 views
2

我正在嘗試使用aiohttp創建一個網站流量模擬器。以下代碼示例異步發出10k個請求。我想知道他們中有多少人同時發生,所以我可以說這是10k用戶同時請求網站的模型。如何確定每秒使用aiohttp的請求數?

如何確定併發網絡請求的數量,或者如何確定aiohttp每秒請求多少個請求?有沒有辦法實時調試/分析併發請求的數量?

有沒有更好的方法來使用任何其他編程語言來建模網絡流量模擬器?

import asyncio 
import aiohttp 

async def fetch(session, url): 
    with aiohttp.Timeout(10, loop=session.loop): 
     async with session.get(url) as response: 
      return await response.text() 

async def run(r): 
    url = "http://localhost:3000/" 
    tasks = [] 

    # Create client session that will ensure we dont open new connection 
    # per each request. 
    async with aiohttp.ClientSession() as session: 
     for i in range(r): 
      html = await fetch(session, url) 
      print(html) 


# make 10k requests per second ?? (not confident this is true) 
number = 10000 
loop = asyncio.get_event_loop() 
loop.run_until_complete(run(number)) 

回答

1

嗨首先有原代碼中的錯誤:

async with aiohttp.ClientSession() as session: 
    for i in range(r): 
     # This line (the await part) makes your code wait for a response 
     # This means you done 1 concurent request 
     html = await fetch(session, url) 

如果你解決,你會得到你想要的錯誤 - 所有的請求都將在同一時間啓動。

你要錘擊服務 - 除非使用信號量/隊列。

無論如何,如果這就是你想要你可以使用這個東西:

import asyncio 
import aiohttp 
import tqdm 


async def fetch(session, url): 
    with aiohttp.Timeout(10, loop=session.loop): 
     async with session.get(url) as response: 
      return await response.text() 


async def run(r): 
    url = "http://localhost:3000/" 
    tasks = [] 
    # The default connection is only 20 - you want to stress... 
    conn = aiohttp.TCPConnector(limit=1000) 
    tasks, responses = [], [] 
    async with aiohttp.ClientSession(connector=conn) as session: 
     tasks = [asyncio.ensure_future(fetch(session, url)) for _ in range(r)] 
     #This will show you some progress bar on the responses 
     for f in tqdm.tqdm(asyncio.as_completed(tasks), total=len(tasks)): 
      responses.append(await f) 
    return responses 

number = 10000 
loop = asyncio.get_event_loop() 
loop.run_until_complete(run(number)) 

感謝asyncio aiohttp progress bar with tqdm爲tqdm :)

我還建議您閱讀https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html以更好地理解如何協同程序的工作。