web服务的架构以及特点
使用线程池ThreadPoolExecutor加速
加速前
tmp/05.falsk_thread_pool.py
这三种模拟的场景(读文件、读数据库、访问API)都是IO,使用sleep就相当于做了一次IO
import flask
import json
import time
app = flask.Flask(__name__)
def read_file():
time.sleep(0.1)
return "file result"
def read_db():
time.sleep(0.2)
return "db result"
def read_api():
time.sleep(0.3)
return "api result"
@app.route("/")
def index():
result_file = read_file()
result_db = read_db()
result_api = read_api()
return json.dumps({
"result_file": result_file,
"result_db": result_db,
"result_api": result_api
})
if __name__ == '__main__':
app.run()
使用postman请求的时间:三次都是6s多一点点,和我们设定的时间大体一致
加速后
import flask
import json
import time
from concurrent.futures import ThreadPoolExecutor
app = flask.Flask(__name__)
pool = ThreadPoolExecutor()
def read_file():
time.sleep(0.1)
return "file result"
def read_db():
time.sleep(0.2)
return "db result"
def read_api():
time.sleep(0.3)
return "api result"
@app.route("/")
def index():
result_file = pool.submit(read_file)
result_db = pool.submit(read_db)
result_api = pool.submit(read_api)
return json.dumps({
"result_file": result_file.result(),
"result_db": result_db.result(),
"result_api": result_api.result()
})
if __name__ == '__main__':
app.run()
使用postman请求后的结果,发现只有300ms多一点,变为原来多一半。其实是取最长的时间,原来的比较短的两个时间的操作都是在最长时间内完成的