往期文章:
web服务的架构以及特点![](http://image109.360doc.com/DownloadImg/2023/10/1313/273742214_1_20231013013939523_wm.png) web后台服务的特点: - web服务对响应时间要求非常高,比如要求200ms返回
- web服务有大量的依赖IO操作的调用,比如磁盘文件、数据库、远程API
使用线程池ThreadPoolExecutor加速使用线程池ThreadPoolExecutor的好处: - 方便的将磁盘文件、数据库、远程API的IO调用并发执行
- 线程池的线程数目不会无限创建(导致系统挂掉),具有防御功能
代码用FastAPI实现Web服务并实现加速不使用进程池方式from fastapi import FastAPI import time
app = FastAPI()
def read_file(): time.sleep(0.1) return "result_file"
def read_db(): time.sleep(0.2) return "read_db"
def read_api(): time.sleep(0.3) return "read_api"
@app.get("/") def index(): return { "result_file":read_file(), "read_db":read_db(), "read_api":read_api() }
if __name__ == "__main__": import uvicorn uvicorn.run(app)
运行结果如下:![](http://image109.360doc.com/DownloadImg/2023/10/1313/273742214_2_20231013013939898_wm.png) 使用进程池方式from fastapi import FastAPI import time from concurrent.futures import ThreadPoolExecutor
app = FastAPI() pool = ThreadPoolExecutor()
def read_file(): time.sleep(0.1) return "result_file"
def read_db(): time.sleep(0.2) return "read_db"
def read_api(): time.sleep(0.3) return "read_api"
@app.get("/") def index(): result_file = pool.submit(read_file) result_db = pool.submit(read_db) result_api = pool.submit(read_api) return { "result_file":result_file.result(), "read_db":result_db.result(), "read_api":result_api.result() }
if __name__ == "__main__": import uvicorn uvicorn.run(app)
运行结果如下:![](http://image109.360doc.com/DownloadImg/2023/10/1313/273742214_3_20231013013940304_wm.png)
|