flask + gevent + multiprocess + wsgi实现高并发接口

发布时间 2023-09-01 14:19:50作者: 左岸丶

Flask + 多进程 + 协程了。 8核虚拟机最高QPS高达1W5。

使用的时候务必注意一下 “”“进程“”“ 安全就行了。

参考代码如下,Flask gevent 多进程WSGI(非gunicorn)

# coding: utf-8
# code by https://cpp.la, 2020-04-20
# flask + gevent + multiprocess + wsgi

from flask import Flask, request
from multiprocessing import cpu_count, Process
from gevent import monkey
from gevent.pywsgi import WSGIServer

monkey.patch_all()
app = Flask(__name__)


@app.route("/api", methods=['GET', 'POST'])
def api():
    args = request.json
    # print(args)
    return args


def run(MULTI_PROCESS):
    if MULTI_PROCESS == False:
        WSGIServer(('0.0.0.0', 8080), app).serve_forever()
    else:
        mulserver = WSGIServer(('0.0.0.0', 8080), app)
        mulserver.start()

        def server_forever():
            mulserver.start_accepting()
            mulserver._stop_event.wait()

        for i in range(cpu_count()):
            p = Process(target=server_forever)
            p.start()


if __name__ == "__main__":
    # 单进程 + 协程
    # run(False)
    # 多进程 + 协程
    run(True)