Python 异步编程:asyncio 与 FastAPI 实战
·
Python 异步编程:asyncio 与 FastAPI 实战
1. 异步编程基础
- 核心概念:通过非阻塞 I/O 操作提升并发性能,避免线程切换开销
- 关键组件:
- 协程 (Coroutine):使用
async def定义的异步函数 - 事件循环 (Event Loop):任务调度核心
- 异步 I/O 库:如
aiohttp、aiomysql
- 协程 (Coroutine):使用
- 性能优势:单线程处理数千并发连接,吞吐量公式:
$$ \text{吞吐量} = \frac{\text{并发连接数}}{\text{平均响应时间}} $$
2. asyncio 核心机制
import asyncio
async def fetch_data(url: str):
print(f"Start fetching: {url}")
await asyncio.sleep(2) # 模拟 I/O 操作
return f"Data from {url}"
async def main():
tasks = [
asyncio.create_task(fetch_data("https://api1.com")),
asyncio.create_task(fetch_data("https://api2.com"))
]
results = await asyncio.gather(*tasks)
print(f"Results: {results}")
# 启动事件循环
asyncio.run(main())
关键方法:
asyncio.create_task():创建并发任务asyncio.gather():并行执行任务组asyncio.sleep():非阻塞等待
3. FastAPI 异步集成
特性对比:
| 框架 | 异步支持 | 性能 (req/s) | 学习曲线 |
|---|---|---|---|
| Flask | ❌ | ~1.5k | 平缓 |
| FastAPI | ✅ | ~12k | 中等 |
实战示例:异步 API 服务
from fastapi import FastAPI
import asyncio
app = FastAPI()
async def simulate_db_query():
await asyncio.sleep(0.5) # 模拟数据库查询
return {"data": [1, 2, 3]}
@app.get("/async-data")
async def get_data():
return await simulate_db_query()
# 启动命令:uvicorn main:app --reload
4. 性能优化技巧
- 连接池管理:
from aiopg.sa import create_engine async def get_db(): engine = await create_engine("postgresql://user:pass@localhost/db") async with engine.acquire() as conn: result = await conn.execute("SELECT * FROM table") - 超时控制:
from asyncio import TimeoutError try: await asyncio.wait_for(fetch_data(), timeout=3.0) except TimeoutError: print("Request timed out") - 错误处理:
@app.get("/items/{id}") async def read_item(id: int): try: item = await db.get(id) return item except ItemNotFound: raise HTTPException(status_code=404)
5. 压测对比
使用 Locust 测试 1000 并发:
- 同步端点:平均响应 $ \approx 650\text{ms} $
- 异步端点:平均响应 $ \approx 85\text{ms} $
资源消耗降低 $ \approx 70% $
6. 最佳实践
- 避免阻塞操作:CPU 密集型任务需用
run_in_executor - 中间件异步化:认证/日志使用
async def - 监控工具:集成 Prometheus + Grafana
- 部署方案:
# 生产环境启动 uvicorn main:app --workers 4 --port 8000
应用场景:实时数据处理、高频交易接口、物联网消息推送等需要高并发的系统。通过异步架构,可显著提升资源利用率,在同等硬件条件下实现 $ \times 5 \sim 10 $ 的吞吐量增长。
更多推荐
所有评论(0)