from fastapi import FastAPI, BackgroundTasks
from concurrent.futures import ThreadPoolExecutor
import asyncio
import time
import threading
import uvicorn
app = FastAPI()
# 创建一个线程池
executor = ThreadPoolExecutor(max_workers=4)
def long_running_task(task_id: int):
"""模拟一个长时间运行的任务"""
print(f"Task {task_id} started in thread {threading.current_thread().name}")
if task_id == 1:
time.sleep(60)
elif task_id == 2:
time.sleep(10)
print(f"Task {task_id} completed in thread {threading.current_thread().name}")
return {"result": f"Task {task_id} is done"}
async def run_in_executor(task_id: int):
# 使用 asyncio.get_running_loop() 获取当前正在运行的事件循环
loop = asyncio.get_running_loop()
print("Using asyncio.get_running_loop()")
# 提交任务到线程池并等待结果
result = await loop.run_in_executor(executor, long_running_task, task_id)
return result
@app.get("/test_1/")
async def test_1():
result = await run_in_executor(1)
return result
@app.get("/test_2/")
async def test_2():
result = await run_in_executor(2)
return result
@app.on_event("startup")
async def startup_event():
# 在应用程序启动时执行一些初始化操作
print("Application startup")
@app.on_event("shutdown")
async def shutdown_event():
# 在应用程序关闭时执行一些清理操作
print("Application shutdown")
executor.shutdown(wait=True) # 确保所有线程池中的任务完成后再关闭
def create_and_run_new_loop():
# 创建一个新的事件循环
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
# 运行一个简单的协程
async def simple_coroutine():
print("Running simple coroutine in new event loop")
await asyncio.sleep(1)
print("Simple coroutine completed")
new_loop.run_until_complete(simple_coroutine())
new_loop.close()
@app.get("/run_new_loop/")
def run_new_loop(background_tasks: BackgroundTasks):
# 将新事件循环的创建和运行放到后台任务中
background_tasks.add_task(create_and_run_new_loop)
return {"message": "New event loop creation and execution started"}
if __name__ == "__main__":
# 使用 asyncio.run() 来运行主程序入口
import uvicorn
uvicorn.run("server:app", host="0.0.0.0", port=1400, reload=True)
FastAPI多线程
最新推荐文章于 2025-04-23 09:47:39 发布