Python_asyncio异步编程深度实战
Python asyncio 异步编程深度实战:从原理到高性能并发模式作者:Crown_22| AI Agent 自动化工作流开发者 | 技术分享前言异步编程是 Python 开发者必须掌握的技能,尤其是在构建 AI Agent、Web 服务、爬虫系统时。但很多开发者对 asyncio 的理解停留在async/await语法层面,对其底层原理和高级用法知之甚少。我在实际项目中用 asyncio 构建过多个高并发系统,踩过无数坑。今天把经验分享出来,帮你真正掌握 Python 异步编程。一、为什么需要异步?1.1 同步的痛点importtimeimportrequestsdeffetch_urls(urls):"""同步方式抓取多个URL"""results=[]forurlinurls:response=requests.get(url)# 阻塞等待results.append(response.text)returnresults# 抓取10个URL,每个耗时1秒,总共需要10秒urls=[f"https://httpbin.org/delay/1"for_inrange(10)]start=time.time()results=fetch_urls(urls)print(f"同步耗时:{time.time()-start:.2f}秒")# ~10秒1.2 异步的优势importasyncioimportaiohttpimporttimeasyncdeffetch_urls_async(urls):"""异步方式抓取多个URL"""asyncwithaiohttp.ClientSession()assession:tasks=[session.get(url)forurlinurls]responses=awaitasyncio.gather(*tasks)return[awaitr.text()forrinresponses]# 抓取10个URL,总共只需~1秒urls=[f"https://httpbin.org/delay/1"for_inrange(10)]start=time.time()results=asyncio.run(fetch_urls_async(urls))print(f"异步耗时:{time.time()-start:.2f}秒")# ~1秒核心区别:同步是串行等待,异步是并发执行。二、asyncio 核心概念2.1 协程(Coroutine)# 定义协程asyncdefhello():print("Hello")awaitasyncio.sleep(1)# 挂起,让出控制权print("World")# 调用协程返回协程对象(不会立即执行)coro=hello()print(type(coro))# class 'coroutine'# 执行协程asyncio.run(hello())2.2 事件循环(Event Loop)importasyncioasyncdeftask(name,delay):print(f"任务{name}开始")awaitasyncio.sleep(delay)print(f"任务{name}完成")returnf"{name}的结果"asyncdefmain():# 创建多个任务tasks=[asyncio.create_task(task("A",2)),asyncio.create_task(task("B",1)),asyncio.create_task(task("C",3))]# 等待所有任务完成results=awaitasyncio.gather(*tasks)print(f"结果:{results}")asyncio.run(main())2.3 Task vs Futureasyncdefdemo():# Task 是 Future 的子类task=asyncio.create_task(some_coroutine())# 可以取消task.cancel()# 可以等待result=awaittask# 可以添加回调task.add_done_callback(lambdat:print(f"完成:{t.result()}"))三、高级并发模式3.1 Semaphore 信号量控制并发数importasyncioimportaiohttpasyncdeffetch_with_limit(urls,max_concurrent=5):"""限制并发数的异步抓取"""semaphore=asyncio.Semaphore(max_concurrent