python3 异步并发
1. TCPConnector 链接池
| import asyncio |
| from aiohttp import ClientSession, TCPConnector |
| async def aiohttp_get(): |
| url = 'url' |
| conn = TCPConnector(limit=10) # 限制同时链接数,连接默认是100,limit=0 无限制 |
| async with ClientSession(connector=conn) as session: |
| async with session.get(url) as response: |
| html = await response.text() |
| return html |
| |
2. Semaphore 信号量
| from aiohttp import ClientSession |
| import asyncio |
| |
| |
| async def hello(sem, url): |
| |
| async with sem: |
| async with ClientSession() as session: |
| async with session.get(f'http://localhost:8080/{url}') as response: |
| r = await response.read() |
| print(r) |
| await asyncio.sleep(1) |
| |
| |
| def main(): |
| loop = asyncio.get_event_loop() |
| tasks = [] |
| sem = asyncio.Semaphore(5) |
| for i in range(100000): |
| task = asyncio.ensure_future(hello(sem, i)) |
| tasks.append(task) |
| |
| feature = asyncio.ensure_future(asyncio.gather(*tasks)) |
| loop.run_until_complete(feature) |
| |
| if __name__ == "__main__": |
| main() |
| |
https://blog.csdn.net/joson1234567890/article/details/105762195
https://cloud.tencent.com/developer/article/1787184
https://blog.csdn.net/whatday/article/details/106886717
https://www.liujiangblog.com/course/python/83
https://python-parallel-programmning-cookbook.readthedocs.io/zh_CN/latest/chapter4/05_Task_manipulation_with_Asyncio.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY