1. 程式人生 > >使用uWSGI和nginx如何設定連線超時時間

使用uWSGI和nginx如何設定連線超時時間

轉載自:https://www.jianshu.com/p/f5ee6b6b7e54

 

前段時間做一個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_timeout time;
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;

以此類推。