测试代码
# -*- coding: utf-8 -*- import time from concurrent.futures import ThreadPoolExecutor from flask import Flask, request executor = ThreadPoolExecutor() app = Flask(__name__) # 模拟耗时任务 def run_job(name): time.sleep(5) print('run_job complete', name) @app.route('/task') def run_task(): """ 同步执行 http://127.0.0.1:5000/task """ name = request.args.get('name') run_job(name=name) return {'ret': 'ok'} @app.route('/async_task') def run_async_task(): """ 异步执行 http://127.0.0.1:5000/async_task """ name = request.args.get('name') executor.submit(run_job, name=name) return {'ret': 'ok'} if __name__ == '__main__': app.run(debug=True)
apache2-utils压力测试工具测试:
# 使用说明: $ ab -n 请求数 -c 并发数 URL # 同步执行任务 $ ab -n 100 -c 10 http://127.0.0.1:5000/task Time taken for tests: 55.100 seconds # 异步执行任务 $ ab -n 100 -c 10 http://127.0.0.1:5000/async_task Time taken for tests: 0.097 seconds