使用Nginx对Flask服务进行负载均衡,提高Flask程序性能
部署
首先准备一个flask程序,名字f_show_api.py
# -*- coding: utf-8 -*-
# @Time : 2019/9/18 9:45
# @Author :
import logging
import time
import gevent.pywsgi
import gevent.monkey
from flask import Flask, request
gevent.monkey.patch_all()
app = Flask(__name__)
app.config["SECRET_KEY"] = "123456"
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(message)s",
level=logging.DEBUG)
@app.route("/f_api", methods=["GET", "POST"])
def f_api():
data = request.values
msg = data.get('msg', 'hello world')
return msg
if __name__ == '__main__':
# app.run(host='0.0.0.0', port=8812)
gevent_server = gevent.pywsgi.WSGIServer(('0.0.0.0', 8812), app)
gevent_server.serve_forever()
安装Nginx和uWSGI
yum install nginx
pip3 install uwsgi
在项目的目录(/data/sitemap/)创建一个uwsgi.ini的配置文件
[uwsgi]
#配合nginx使用
socket = 127.0.0.1:8812
#项目路径 /data/sitemap
chdir = /data/sitemap
#wsgi文件 f_show_api就是flask启动文件去掉后缀名 app是f_show_api.py里面的Flask对象
module = f_show_api:app
# 指定工作进程
processes = 8
#主进程
master = true
#每个工作进程有2个线程
threads = 2
#指的后台启动 日志输出的地方
daemonize = uwsgi.log
#保存主进程的进程号
pidfile = uwsgi.pid
# 修改项目自动重启
# touch-reload=/data/sitemap
修改Nginx配置文件 vim /etc/nginx/nginx.conf
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /usr/share/nginx/html;
include /etc/nginx/default.d/*.conf;
# 这里修改为uwsgi_params,以及相应需要转发的端口
location / {
include uwsgi_params;
uwsgi_pass 127.0.0.1:8812;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
启动Nginx和uWSGI
# 启动Nginx服务
systemctl start nginx.service
# 设置Nginx为开机启动
systemctl enable nginx.service
uwsgi --ini /data/sitemap/uwsgi.ini
#### 重启:
# uwsgi --reload /data/sitemap/uwsgi.pid
#### 停止:
# uwsgi --stop /data/sitemap/uwsgi.pid
# 查看uWSGI服务
# ps -ef | grep -v grep | grep uwsigi
在浏览器中访问
发送一个post请求