FastAPI多线程

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值