Nginx 负载均衡 NodeJS~

247 阅读2分钟

负载均衡的目的是为了解决单个节点压力过大,造成Web服务响应过慢,严重的情况下导致服务瘫痪,无法正常提供服务。

假设 基于 本博客内 Node.js+MySQL 服务已经跑在 如下端口,并配置 Nginx 转发:

upstream ht-server {
    server 0.0.0.0:3004;
    server 0.0.0.0:3001;
    server 0.0.0.0:3002;
    server 0.0.0.0:3003;
}
server
{
    listen 80;#监听端口
    #server_name 192.168.1.30;#域名
    index index.html index.htm index.php;
    root /usr/local/webserver/nginx/pages;#站点目录
    
    location /ht/ {
       proxy_pass http://ht-server/;
    }

}

假若有以下 查询用户接口,利用 ab 测试工具 测试 负载均衡 ab -c 1000 -n 20000 http://localhost/ht/users

本地环境测试nodeJS+Express+mysql, 设置连接池,4进程 Nginx负载均衡,得出结论:1000并发20000个请求 10.566秒完成 0失败。

This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)
Completed 2000 requests
Completed 4000 requests
Completed 6000 requests
Completed 8000 requests
Completed 10000 requests
Completed 12000 requests
Completed 14000 requests
Completed 16000 requests
Completed 18000 requests
Completed 20000 requests
Finished 20000 requests

Server Software: nginx/1.6.2
Server Hostname: localhost
Server Port: 80

Document Path: /ht/users
Document Length: 692 bytes

Concurrency Level: 1000
Time taken for tests: 10.566 seconds
Complete requests: 20000
Failed requests: 0
Write errors: 0
Total transferred: 19960000 bytes
HTML transferred: 13840000 bytes
Requests per second: 1892.92 [#/sec] (mean)
Time per request: 528.283 [ms] (mean)
Time per request: 0.528 [ms] (mean, across all concurrent requests)
Transfer rate: 1844.86 [Kbytes/sec] received

Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 7 14.0 0 73
Processing: 1 508 377.1 481 1492
Waiting: 0 506 376.9 478 1492
Total: 1 515 376.3 487 1492

Percentage of the requests served within a certain time (ms)
50% 487
66% 677
75% 793
80% 922
90% 1021
95% 1142
98% 1327
99% 1386
100% 1492 (longest request)