centos nginx代理无返回值的问题

今天跟前端调试的时候发现,在用户登录的一系列请求中,有一个请求没有返回值,开始的时候认为是代码逻辑出错,但单独调试代码发现功能没有问题,然后就怀疑是否是nginx拦截掉了返回值,故而在nginx中加入打印返回值的功能

一.安装打印返回值插件

1.安装openresty

nginx不具有打印返回值的功能,需借用openresty实现,官网也是如此推荐的:https://www.nginx.com/resources/wiki/modules/lua/

按照官网步骤安装即可:http://openresty.org/cn/linux-packages.html

shell > sudo yum install yum-utils
shell > sudo yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
shell > sudo yum -y install openresty

2.修改nginx 配置

在openresty安装目录下集成了nginx,直接修改其下的nginx.conf配置

shell > vim /usr/local/openresty/nginx/conf/nginx.conf
http {
    include       mime.types;
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$resp_body"';

    access_log  logs/access.log main;

    server {
        listen 80;
        server_name 10.130.161.42;
        set $resp_body "";
        location ^~ /hotpot-dev/ {
          lua_need_request_body on;
            body_filter_by_lua '
                local resp_body = string.sub(ngx.arg[1], 1, 1000)
                ngx.ctx.buffered = (ngx.ctx.buffered or "") .. resp_body
                if ngx.arg[2] then
                    ngx.var.resp_body = ngx.ctx.buffered
                end
            ';
        }

    }
}

启动nginx

/usr/local/openresty/nginx/sbin/nginx -c /usr/local/openresty/nginx/conf/nginx.conf

二.查看nginx access.log

通过查看access.log发现,没有返回值的请求,log格式如下:

10.130.161.63 - - [16/Oct/2018:11:43:54 +0800] "POST /test-dev/protocol?uid=10000232833 HTTP/1.1" 499 0 "https://apps-123.apps.fbsbx.com/instant-bundle/123/123/index.html?psev=1&source=fbinstant-123&IsMobileWeb=0" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0" "-" ""

最后一列为"",表示没有返回信息,http状态码为499,通过网络查找,发现http状态码499代表客户端与服务端断开了连接,可以通过配置proxy_ignore_client_abort解决,具体配置如下:

location ^~ /hotpot-dev/ {
          proxy_pass   http://testDev;
          proxy_ignore_client_abort   on;
	}

重新nginx,发现问题仍然没有解决,查看access.log,发现已经有返回值了,由此可以推断前端也断开发连接,故此接收不到返回值,而之所以会出现http 499这个状态码,是由于瞬间同一个用户有大量的请求连接到nginx,导致nginx主动断开了连接,proxy_ignore_client_abort,客户端主动断掉连接之后,Nginx 会等待后端服务器处理完(或者超时),然后记录“后端的返回信息”到日志,但不推荐使用这个参数,因为这样当有大量瞬间断开的请求时,后端会默默地全部处理,比较浪费资源,而且并发压力比较大时,用这种方法将压垮机器,而且使用这个参数后,客户端仍然处于断开状态,无法从根本上解决问题

之后与前端确认了其确实是在同一帧发送了多个请求到服务器,导致的nginx与客户端连接中断,当前端改为前一个请求处理完成后再发送下一个请求时,这个问题得以解决

猜你喜欢

转载自blog.csdn.net/feiying00544/article/details/83095654