tornado使用长连接并运行在nginx反向代理后面

使用nginx作为tornado的反向代理是非常不错的,因为python的GIL不能充分利用多核资源。

可以在一台机器上运行多个python进程,监听多个端口,前面用nginx做代理。

下面给出一个nginx的配置例子,例子中tornado使用长连接,运行聊天服务器。

 1 upstream chat_cluster{
 2     server 127.0.0.1:10000;
 3     server 127.0.0.1:10001;
 4     ip_hash;
 5     keepalive 1024;
 6 }
 7 
 8 server
 9 {
10     listen 80;
11     server_name chat.rootk.com;
12 
13     location / {
14         proxy_pass http://chat_cluster;
15         proxy_http_version 1.1;
16         # very important, nginx will waitting for the response from tornado
17         # if the time have passed more than 7200, nginx send http 504 to client
18         proxy_read_timeout 7200;
19         proxy_set_header Connection "";
20         proxy_set_header Host $host;
21         proxy_set_header X-Real-Ip $remote_addr;
22         proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
23     }
24 }

注意红色的一行配置,它说明由nginx向tornado请求了长连接以后,等到7200秒之后,如果tornado还没有返回。

则nginx返回504 Gateway Timeout给客户端浏览器。

如果没有这一行,nginx则在数秒内返回HTTP 504给客户端。

原文地址:https://www.cnblogs.com/huazi/p/2950700.html