2.发起一个session请求
node2:/root/python/20200525#cat t300.py
import asyncio,aiohttp
# -*- coding: utf-8 -*-
async def fetch_async(url):
print(url)
async with aiohttp.ClientSession() as session:#协程嵌套,只需要处理最外层协程即可fetch_async
async with session.get(url) as resp:
print(resp.url)
print(resp.status)
print(await resp.text())#因为这里使用到了await关键字,实现异步,所有他上面的函数体需要声明为异步async
tasks = [fetch_async('http://192.168.137.3:9000/test111/'), fetch_async('http://192.168.137.3:9000/test222/'),fetch_async('http://192.168.137.3:9000/test333/')]
event_loop = asyncio.get_event_loop()
results = event_loop.run_until_complete(asyncio.gather(*tasks))
event_loop.close()
node2:/root/python/20200525#time python3 t300.py
http://192.168.137.3:9000/test111/
http://192.168.137.3:9000/test222/
http://192.168.137.3:9000/test333/
http://192.168.137.3:9000/test111/
200
test111 success
http://192.168.137.3:9000/test222/
200
test222 success
http://192.168.137.3:9000/test333/
200
test333 success
real 0m7.368s
user 0m0.322s
sys 0m0.033s