美文网首页
用nginx负载均衡,提高并发

用nginx负载均衡,提高并发

作者: 蟹老板爱写代码 | 来源:发表于2018-05-16 23:45 被阅读0次

上篇文章说到用ab做压力测试,单台服务器出现cpu瓶颈。
为了提高并发,可以从两方面扩展,纵向扩展(提升单台服务器性能),横向扩展(增加机器)。
纵向扩展,成本是比较大的,而且容易到顶,随着业务增加,还是撑不住。
所以我们要做分布式方案,这样可以随着业务扩展,租用更多机器来扛住压力。

目前软负载比较简单的方式就是用nginx了,当然你也可以硬负载,不过我没接触过,只是听过而已,据说很贵。

那我下面就介绍nginx配置方法。
我两台机器配置都没1核1G内存。
直接看nginx配置吧

upstream backend // 这个名字随便起,用于下面做反向代理
{
  server 10.104.136.40; // A机器的地址
  server 10.104.243.10; // B机器的地址
}

// 监听80端口,做反向代理
server {
    listen       80 default_server;
#    listen       [::]:80 default_server;
    server_name  _;
    root         /usr/share/nginx/html;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

        location / {
            proxy_pass  http://backend;  // upstream里定义的名字
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            root   html;
            index  index.html index.htm;
        }

    error_page 404 /404.html;
        location = /40x.html {
    }

    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }

}

就这样,reload nginx就生效了,为了测试是否成功负载,可以在两个应用返回不同信息,用浏览器访问,看是否会自动切换。

如果测试时,出现较多的异常,可以查看nginx 的error log,定位问题
如果出现1024 worker_connections are not enough
可以修改/etc/nginx/nginx.conf

events {
    worker_connections 20000;
}

下面为3000个并发,用分布式方案的结果,比单机平均处理时间降低了1秒。

Concurrency Level:      3000
Time taken for tests:   11.291 seconds
Complete requests:      20000
Failed requests:        0
Total transferred:      2400000 bytes
HTML transferred:       0 bytes
Requests per second:    1771.31 [#/sec] (mean)
Time per request:       1693.658 [ms] (mean)
Time per request:       0.565 [ms] (mean, across all concurrent requests)
Transfer rate:          207.58 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0  204 892.5      0    7028
Processing:     1  279 587.7    134    7020
Waiting:        1  279 587.7    134    7020
Total:          1  483 1111.1    175    8710

Percentage of the requests served within a certain time (ms)
  50%    175
  66%    245
  75%    343
  80%    411
  90%   1187
  95%   1972
  98%   4294
  99%   7279
 100%   8710 (longest request)

相关文章

网友评论

      本文标题:用nginx负载均衡,提高并发

      本文链接:https://www.haomeiwen.com/subject/wccvdftx.html