使用uWSGI和nginx如何设置连接超时时间?

前段时间做一个django的项目,因为之前项目只是一个后台程序,因此数据库设计的并不满足后面新添加的前端的需求,所以查询显示什么的特别冗余,造成了大量的坑。今天就分享一个爬坑的过程。


1先看看需求

项目要求在一个报告中显示一个列表,这个列表包含这个报告中包含的所有任务文件。在发生问题这个报告中包含了大约200个文件,平均每个文件的大小差不多在1.5M左右。对于每个文件,发送请求的时候包含两个参数,一个是文件名,另一个是文件生成时间。

基本的需求就是这样,结果前端在转了一阵圈圈之后成功返回了500,WTF。

2 如何定位问题

打开nginx的日志(nginx日志默认的路径\var\log\nginx\error.log),输出中由如下这行:

*42 upstream time out(110: Connection timed out) while reading response header from upstream...

日志写的很清楚,就是连接时间超时了。因此决定上网查询如何解决这个问题。

通过nginx官方nginx给出的文档,发现了问题所在。

官方文档

文档中指出:

Syntax:

uwsgi_connect_timeouttime;

Default:

uwsgi_connect_timeout 60s;

Context:

http, server, location

Defines a timeout for establishing a connection with a uwsgi server. It should be noted that this timeout cannot usually exceed 75 seconds.

ok,可以看到,nginx默认的设置时间是60s,如果你的链接时间超过这个了,那必须指明具体提时间。这里官方说最好不要超过75s,那就要看具体实现的水平能否控制在这个范围内了。因为我在这里爬坑,并不想去优化代码,所以设置600s足够。

3 如何修改

修改你的nginx配置文件,我的样例如下:

# interface.conf

# configuration of the server
server {
    # the port your site will be served on
    listen 8099;
    # the domain name it will serve for
    server_name 127.0.0.1;  # substitute your machine's IP address or FQDN
    charset utf-8;

    # max upload size
    client_max_body_size 75M; # adjust to taste

    # Django media
    location /media  {
        alias /home/jason/code/interface/media;  # your Django project's media files - amend as required
    }

    location /static {
        expires 30d;
        autoindex on;
        add_header Cache-Control private;
        alias /home/jason/code/interface/static;   # your Django project's static files - amend as required
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        # 注意这儿,一般这三个配套修改
        uwsgi_send_timeout 600;        # 指定向uWSGI传送请求的超时时间,完成握手后向uWSGI传送请求的超时时间。
        uwsgi_connect_timeout 600;   # 指定连接到后端uWSGI的超时时间。
        uwsgi_read_timeout 600;        # 指定接收uWSGI应答的超时时间,完成握手后接收uWSGI应答的超时时间。
        uwsgi_pass  127.0.0.1:8000;
        include /home/jason/code/interface/conf/uwsgi_params;       # the uwsgi_params file you installed
    }
}

4 一些说明

如果你使用的不是uwsgi,那么你就要注意了,你应该在nginx找到对应的nginx模块介绍。

例如你使用nginx只是作为反向代理,那么你修改的这个时间应该对应调整为:

        # 注意这儿,一般这三个配套修改
        proxy_send_timeout 600;
        proxy_connect_timeout 600;
        proxy_read_timeout 600;

例如你使用的是fastcgi, 那么你修改的这个时间应该对应调整为:

        # 注意这儿,一般这三个配套修改
        fastcgi_send_timeout 600;
        fastcgi_connect_timeout 600;
        fastcgi_read_timeout 600;

以此类推。