【发布时间】:2019-08-03 00:53:56
【问题描述】:
在我的 django 视图中,我有一项很长的任务,需要 120-200 秒才能生成响应。
对于这个特定的视图,Nginx 会在 1 分钟后引发 502 Bad Gateway,并在日志中显示以下错误消息:
[error] 7719#7719: *33 upstream prematurely closed connection while reading response header from upstream,
这是我的 Nginx 配置:
upstream DjangoServer {
server 127.0.0.1:8000;
keepalive 300;
}
location / {
include proxy_params;
proxy_pass http://DjangoServer;
allow all;
proxy_http_version 1.1;
proxy_set_header X-Cluster-Client-Ip $remote_addr;
client_max_body_size 20M;
keepalive_timeout 300;
proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_read_timeout 300;
send_timeout 300;
}
这是我的 uWSGI 配置:
uid=www-data
gid=www-data
http=127.0.0.1:8000
http-keepalive=300
master=1
vacuum=1
workers=2
threads=5
log-5xx=1
注意:
- Nginx 和 uWSGI 适用于所有其他视图。
- Django 开发服务器可以正常运行任务。
- Nginx 502 错误后,uWSGI 继续在后台运行并完成作业,(根据 in view print 语句)。
- 如果我尝试通过浏览器连接到 uWSGI,过一段时间(少于 120 秒)会显示
ERR_EMPTY_RESPONSE。
你可以承担这样的任务
def long_task_view(request):
start_time = time.time()
print(start_time)
# doing stuff
time.sleep(130)
print(time.time() - start_time)
return HttpResponse("The result")
【问题讨论】: