05.24 nginx负载均衡

本文详细介绍Nginx作为负载均衡器的应用配置,包括不同调度算法、健康检查配置及反向代理设置等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一章 集群的优势特点

一些国家重要的计算密集型应用(如:天气预报、核试验模拟等),需要计算机有很强的运算处理能力。以全世界现有的技术,即使是大型机,其计算能力也是有限的,很难单独完成此任务。因为计算时间可能会相当长,也许几天,甚至纪念或更久,因此,对于这类复杂的计算业务,便使用了计算机集群技术,集中有几十上百台,甚至成千上万台计算机进行计算。


第二章 集群的常见分类

负载均衡集群(Load balancing clusters),简称LBC或LB
高可用性集群(High-availability clusters)简称HAC
高性能计算集群(High-performance clusters)简称HPC
网络计算(Grid computing)


第三章 负载均衡集群的作用

  1. 分担用户访问请求及数据流量(负载均衡)。
  2. 保持业务连续性,即7*24小时服务(高可用性)。
  3. 应用于web业务及数据库从库(读)等服务器的业务。
  4. 负载均衡集群典型的开源软件包括LVS、Nginx Haproxy等。

这里写图片描述


第四章 高可用性集群

高可用性集群常用的开源软件包括Keepalived、Hearbeat等
这里写图片描述


第五章 企业中常见软硬件介绍

互联网企业常用的开源集群软件有:Nginx LVS Haproxy Keepalived Hearbeat
应用层(http、https)
传输层(tcp)
互联网企业常用的商业集群硬件有:F5、Netscaler、Radware、A10等。工作模式相当于haproxy的工作模式。
这里写图片描述


第六章 企业中常见软硬件选择

  1. 当企业业务重要,技术力量又薄弱,并且希望出钱购买产品及获取更好的服务时,可以选择硬件负载均衡产品,如F5、Netscaler、Radware等,此类公司多为传统的大兴非互联网企业,如银行、证券、金融、宝马、奔驰等。
  2. 对于门户网站来说,大多会并用软件及硬件产品来分担单一产品的风险,如淘宝、腾讯、新浪等。融资了的企业会购买硬件的产品,如赶集等网站。
  3. 中小型互联网企业,由于起步阶段无利润可赚或者利润很低,会希望通过使用开源免费的方案来解决问题,因此会雇佣专门的运维人员进行维护。

第七章 反向代理与负载均衡概念

严格的说,Nginx仅仅是作为Nginx Proxy反向代理使用的,因此这个反向代理功能表现的效果是负载均衡的效果,所以本文称之为Nginx负载均衡。

普通负载均衡软件,例如LVS。其实现的功能只是对请求数据包的转发(也可能会改成数据包)、传递,其中DR模式明显的特征是从负载均衡下面的节点服务来看,接受到的请求还是来自访问负载均衡器的客户端的真实用户,而反向代理就不一样了,反向代理接收访问用户的请求后,会代理用户重新发起请求代理下的节点服务器,最后把数据返回给客户端用户,在节点服务器看来,访问的节点服务器的客户端用户就是反向代理服务器了,而非真是的的网站访问用户。


第八章 负载均衡的组件模块

Nginx http功能模块模块说明
ngx_http_proxy_moduleproxy代理模块,用于把请求后抛给服务器节点或upstream服务器池。
ngx_http_upstream_module负载均衡该模块,可以实现网站的负载均衡功能及节点的健康检查。创建了一个池子,web服务器

第九章 配置nginx web服务

1. 配置文件修改

worker_processes  1;
events {
        worker_connections  1024;
}
http {
        include       mime.types;
        default_type  application/octet-stream;
        sendfile        on;
        keepalive_timeout  65;
        log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for"';

        server {
                listen       80;
                server_name  www.etiantian.org;
                location / {
                        root   html/www;
                        index  index.html index.htm;
                }
                access_log  logs/access_www.log  main;
        }
        server {
                listen       80;
                server_name  bbs.etiantian.org;
                location / {
                        root   html/bbs;
                        index  index.html index.htm;
                }
                access_log  logs/access_bbs.log  main;
        }
}

2. 创建对应站点目录及首页文件

mkdir -p /application/nginx/html/{www,bbs}
for dir in www bbs;do echo "`ifconfig eth0|egrep -o "10.0.0.[0-9]+"` $dir" >/application/nginx/html/$dir/index.html;done

3. 优雅重启

[root@web02-8 html]# nginx -t
nginx: the configuration file /application/nginx-1.10.2/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.10.2/conf/nginx.conf test is successful
[root@web02-8 html]# nginx -s reload

4. 负载均衡upstream

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;


    upstream server_pools { 
         server 10.0.0.7;
         server 10.0.0.8;
         server 10.0.0.9;
    }       

    server { 
       listen       80;
       server_name  www.etiantian.org;
       location / {
        proxy_pass http://server_pools; 
       }
    }
}

5. weight权重模块

[root@LB01_5 conf]# vim nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;


    upstream server_pools {
         server 10.0.0.7:80 weight=2;
         server 10.0.0.8:80 weight=1;
         server 10.0.0.9:80 weight=1;
    }

    server {
       listen       80;
       server_name  www.etiantian.org;
       location / {
        proxy_pass http://server_pools;
       }
    }
}

6. max_fails fail_timeout

    upstream server_pools {
         server 10.0.0.7:80 weight=4 max_fails=3 fail_timeout=30s;
         server 10.0.0.8:80 weight=4 max_fails=3 fail_timeout=30s;

max_fail 最大的失败连接数,当连接失败后会再继续3次连接
fail_timeout失败连接超时时间,当连接失败超过30s后会尝试重新连接

7. backup

    upstream server_pools {
         server 10.0.0.7:80 weight=4 max_fails=3 fail_timeout=30s;
         server 10.0.0.8:80 weight=4 max_fails=3 fail_timeout=30s;
         server 10.0.0.9:80 weight=4 max_fails=3 fail_timeout=30s backup;
    }
backup备用服务器,当加入backup后不使用该服务器,当其它两台服务器挂掉之后自动使用本服务器。

8. server标签详解

server标签参数说明
server 10.0.0.8:80负载均衡后面的RS配置,可以是IP或域名,如果端口不写,默认是80端口。高并发场景下,IP可换成域名,通过DNS做负载均衡。
weight=1代表服务器的权重默认值是1。权重数字越大表示接受的请求比例越大。
max_fails=1Nginx尝试连接后端主机失败的次数,这个数值是配合proxy_next_upstarem \ fastcgi_next_upstream和memcached_next_upstream这三个参数来使用的,当Nginx接收后端服务器返回的这三个参数定义的状态码时,会将这个请求转发给正常工作的后端服务器,例如404、502、503。max_fails的默认值是1;企业场景:建议2-3次。京东1次,蓝汛10次。根据业务需求去配置
fail_timeout=10s在max_fails定义的失败次数后,距离下次检查的间隔时间,默认是10s;如果max_fails是5,它就检测5次,如果5次都是502。那么,它就会根据fail_timeout的值,等待10s再去检查。还是只检查一次,如果持续502,在不重新加载nginx配置的情况下,每隔10s
backup热备配置(RS节点的高可用),当前面激活的RS都失败后会自动启用热备RS。这标志着这个服务器作为备份服务器,若主服务器全部宕机了,就会向它转发请求;注意,当负载调度算法为ip_hash时,后端服务器在负载均衡调度中的状态不能是weight和backup。
down这标志着服务器永远不适用相当于注释,这个参数可配合ip_hash使用。

第十章 upstream模块调度算法

1. rr轮询(round robin默认调度算法,静态调度算法)
把客户端的请求逐一分配到不同的后端节点服务器,这相当于LVS中的rr算法,如果后端节点服务器宕机(默认情况下nginx只检测80端口),宕机的服务器会被自动从节点服务器池中剔除,以使客户端的用户访问不受影响。新的请求分配给正常的服务器。

2. wrr权重轮询
在rr轮询算法的基础上加上权重,即为权重轮询算法,但是用该算法时候,权重和用户访问成正比,权重值越大,被转发的请求也就越多,可以根据服务器的配置和性能制定权重大小,有效解决新旧服务器溪能不均带来的请求分配问题。

3. least_conn算法
least_conn算法会根据后端节点的连接数来决定分配情况,哪个机器连接数少就分发。

4. url_hash算法
和ip_hash类似,这里是根据访问URL的hash结果来分配请求的,让每个URL定向到同一个后端服务器,后端服务器为缓存服务器时效果显著。在upstream中加入hash语句,server语句中不能写入weight等其他的参数,hash_method使用的hash算法。

5. ip_hash静态调度算法
每个请求按客户端IP的hash结果分配,当新的请求达到时,先将其客户端端IP通过hash算法哈希出一个值,在随后的客户端请求中,客户端IP哈希值只要相同,就会被分配给同一台服务器,该调度算法可以解决动态网页的session共享问题,但有时会导致请求分配不均,即无法保证1:1的负载均衡,因为在国内大多数公司都是NAT上网模式,多个客户端会对应一个外部IP,所以这些客户端都会被分配到同一节点服务器,从而导致请求分配不均。LVS负载均衡的-p参数、Keepalived配置里的persistence_timeout50参数都类似这个nginx里的IP_hash参数。其功能都可以解决动态网页的session共享问题。


第十一章 proxy模块

http proxy模块相关参数说明
proxy_set_header负载均衡请求后面web服务器的时候,请求,响应。
proxy_set_header修改 请求头里面的信息设置http请求header项传给后端服务器节点,例如:可实现让代理后端的服务器节点获取访问客户端用户的真实IP地址。
client_body_buffer_size用户指定客户端请求主体缓冲区大小,此处如了解前文的http请求包的原理就好理解了。
proxy_connect_timeout表示反向代理与后端接单服务器连接的超时时间,即发起握手等候相应的超时时间。
proxy_send_timeout表示代理后端服务器的数据回传时间,即在规定时间之内后端服务器必须传完所有的数据,否则,Nginx将断开这个连接。
proxy_read_timeout设置Nginx从代理的后端服务器获取信息的时间,表示连接建立成功后,Nginx等待后端服务器的响应时间,其实是Nginx已经进入后端的派对只中等候处理的时间。

9. proxy_set_header Host

    server {
       listen       80;
       server_name  bbs.etiantian.org;
       location / {
        proxy_pass http://server_pools;
        proxy_set_header  Host $host;
       }
    }

10. proxy_set_header X-Forwarded-For

    server {
       listen       80;
       server_name  bbs.etiantian.org;
       location / {
        proxy_pass http://server_pools;
        proxy_set_header  Host $host;
        proxy_set_header  X-Forwarded-For $remote_addr;
       }
    }
[root@LB01_5 conf]# vim nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;


    upstream server_pools {
         server 10.0.0.7:80 weight=4 max_fails=3 fail_timeout=30s;
         server 10.0.0.8:80 weight=4 max_fails=3 fail_timeout=30s;
         server 10.0.0.9:80 weight=4 max_fails=3 fail_timeout=30s;
    }

    server {
       listen       80;
       server_name  www.etiantian.org;
       location / {
        proxy_pass http://server_pools;
        proxy_set_header  Host $host;
        proxy_set_header  X-Forwarded-For $remote_addr;
       }
    }
    server {
       listen       80;
       server_name  bbs.etiantian.org;
       location / {
        proxy_pass http://server_pools;
        proxy_set_header  Host $host;
        proxy_set_header  X-Forwarded-For $remote_addr;
       }
    }
}
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    upstream upload_pools {
      server 10.0.0.8:80;
    }

    upstream static_pools {
      server 10.0.0.7:80;
    }

    upstream default_pools {
      server 10.0.0.9:80;
    } 

    server { 
       listen       80;
       server_name  www.etiantian.org;
         location /upload {
             proxy_pass http://upload_pools;  
             proxy_set_header Host $host;
             proxy_set_header X-Forwarded-For $remote_addr;
         }

         location /static {
             proxy_pass http://static_pools;  
             proxy_set_header Host $host;
             proxy_set_header X-Forwarded-For $remote_addr;
         }


         location / {
             proxy_pass http://default_pools;  
             proxy_set_header Host $host;
             proxy_set_header X-Forwarded-For $remote_addr;
         }
    }
}
#!/bin/bash # 配置参数(可根据需要调整) PID=628 # 目标进程PID INTERVAL=1 # 采集间隔(秒) DURATION=300 # 总采集时长(秒) OUTPUT_FILE="thread_data_$(date +%Y%m%d_%H%M%S).csv" # 检查ADB连接 if ! adb devices | grep -q "device$"; then echo "错误:未检测到连接的设备,请确保ADB已连接" exit 1 fi # 写入CSV表头 echo "timestamp,tid,thread_name,cpu_percent,res_kb" > "$OUTPUT_FILE" echo "开始采集PID $PID 的线程数据,持续 $DURATION 秒,输出至 $OUTPUT_FILE..." # 计算采集结束时间 END=$((SECONDS + DURATION)) # 循环采集数据 while [ $SECONDS -lt $END ]; do TIMESTAMP=$(date +%s%3N) # 毫秒级时间戳 # 核心改进: # 1. 用sed过滤ANSI终端控制字符(去除颜色、光标指令) # 2. 用awk提取有效行(过滤标题行、空行) # 3. 动态解析字段(通过关键字定位,避免固定索引错误) adb shell "top -H -p $PID -d 0.1 -n 1" 2>/dev/null | \ sed -r "s/\x1b\[[0-9;]*m//g" | # 移除所有ANSI控制字符 grep -vE "Threads:|Mem:|Swap:|TID|^$" | # 过滤非线程数据行 while read -r line; do # 解析行数据(处理空格分隔,提取关键字段) # 示例行格式:" 5465 system 20 0 11G 43M 15M S 15.3 0.6 5:35.65 SP:img2tensor ..." # 字段含义(按顺序):TID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ THREAD_NAME ... parts=($line) # 按空格分割为数组(自动合并连续空格) # 容错:跳过字段不足的行 if [ ${#parts[@]} -lt 12 ]; then continue fi TID=${parts[0]} CPU=${parts[8]} # %CPU在第9个位置(索引8) RES_STR=${parts[5]} # RES在第6个位置(索引5,如"43M") THREAD_NAME=${parts[11]} # 线程名在第12个位置(索引11) # 转换RES为KB(处理M/K单位,默认0) if [[ $RES_STR =~ ([0-9.]+)([MK]) ]]; then VALUE=${BASH_REMATCH[1]} UNIT=${BASH_REMATCH[2]} if [ "$UNIT" = "M" ]; then RES_KB=$(echo "$VALUE * 1024" | bc | awk '{printf "%.0f", $0}') elif [ "$UNIT" = "K" ]; then RES_KB=$(echo "$VALUE" | bc | awk '{printf "%.0f", $0}') fi else RES_KB=0 # 无效格式时默认为0 fi # 写入CSV(确保字段完整) echo "$TIMESTAMP,$TID,$THREAD_NAME,$CPU,$RES_KB" >> "$OUTPUT_FILE" done sleep $INTERVAL done echo "采集完成!数据已保存至 $OUTPUT_FILE" 记录的csv一点不对 timestamp,tid,thread_name,cpu_percent,res_kb 1753787679283,4931,SP:img2tensor,0.0,27648 1753787679283,731,HwBinder:628_1,0.0,27648 1753787679283,732,HwBinder:628_2,0.0,27648 1753787679283,628,hidl_service@1. [?25h[?25h[?25h,0.0,27648 1753787680671,4931,SP:img2tensor,0.0,27648 1753787680671,731,HwBinder:628_1,0.0,27648 1753787680671,732,HwBinder:628_2,0.0,27648 1753787680671,628,hidl_service@1. [?25h[?25h[?25h,0.0,27648 1753787682043,4931,SP:img2tensor,0.0,27648 1753787682043,731,HwBinder:628_1,0.0,27648 1753787682043,732,HwBinder:628_2,0.0,27648 1753787682043,628,hidl_service@1. [?25h[?25h[?25h,0.0,27648 1753787683409,10010,hidl_service@1. ,66.6,31744 1753787683409,9996,SP:img2tensor,11.1,31744 1753787683409,9990,SP:img2tensor,7.4,31744 1753787683409,9997,SP:img2tensor,7.4,31744 1753787683409,9991,SP:img2tensor,7.4,31744 1753787683409,4931,SP:img2tensor,7.4,31744 1753787683409,9992,SP:img2tensor,3.7,31744 1753787683409,10101,streampipe/9996 ,0.0,31744 1753787683409,10022,streampipe/9991 ,0.0,31744 1753787683409,9994,SP:img2tensor,0.0,31744 1753787683409,9993,streampipe/9993 ,0.0,31744 1753787683409,9995,SP:img2tensor,0.0,31744 1753787683409,9998,stream_callback ,0.0,31744 正确的应该如下 Threads: 17 total, 1 running, 16 sleeping, 0 stopped, 0 zombie Threads: 17 total, 2 running, 15 sleeping, 0 stopped, 0 zombie Tasks: 1 total, 0 running, 1 sleeping, 0 stopped, 0 zombie Threads: 17 total, 1 running, 16 sleeping, 0 stopped, 0 zombie Mem: 7315424K total, 6904284K used, 411140K free, 8104K buffers Swap: 3969620K total, 1024K used, 3968596K free, 1888448K cached 800%cpu 314%user 2%nice 170%sys 291%idle 0%iow 20%irq 3%sirq 0%host TID USER [CPU]%CPU %MEM TIME+ THREAD PROCESS 8097 system 7 67.0 0.5 3:15.31 hidl_service@1. vendor.vt.pipeline.hidl_service@1.0-service 4931 system 3 12.0 0.5 13:38.87 SP:img2tensor vendor.vt.pipeline.hidl_service@1.0-service 8085 system 5 11.0 0.5 0:22.39 SP:img2tensor vendor.vt.pipeline.hidl_service@1.0-service 8084 system 5 8.0 0.5 0:23.38 SP:img2tensor vendor.vt.pipeline.hidl_service@1.0-service 8082 system 5 8.0 0.5 0:22.42 SP:img2tensor vendor.vt.pipeline.hidl_service@1.0-service 8087 system 5 7.0 0.5 0:22.86 SP:img2tensor vendor.vt.pipeline.hidl_service@1.0-service 8088 system 5 6.0 0.5 0:22.73 SP:img2tensor vendor.vt.pipeline.hidl_service@1.0-service 8083 system 5 6.0 0.5 0:22.99 SP:img2tensor vendor.vt.pipeline.hidl_service@1.0-service 8086 system 5 6.0 0.5 0:22.55 SP:img2tensor vendor.vt.pipeline.hidl_service@1.0-service 8081 system 5 5.0 0.5 0:22.75 SP:img2tensor vendor.vt.pipeline.hidl_service@1.0-service 8089 system 5 2.0 0.5 0:05.24 stream_callback vendor.vt.pipeline.hidl_service@1.0-service 8090 system 5 2.0 0.5 0:05.27 stream_callback vendor.vt.pipeline.hidl_service@1.0-service 8185 system 3 0.0 0.5 0:00.00 streampipe/8081 vendor.vt.pipeline.hidl_service@1.0-service 8124 system 4 0.0 0.5 0:00.00 streampipe/8083 vendor.vt.pipeline.hidl_service@1.0-service 732 system 0 0.0 0.5 0:00.41 HwBinder:628_2 vendor.vt.pipeline.hidl_service@1.0-service 731 system 4 0.0 0.5 0:00.00 HwBinder:628_1 vendor.vt.pipeline.hidl_service@1.0-service 628 system 3 0.0 0.5 0:00.47 hidl_service@1. vendor.vt.pipeline.hidl_service@1.0-service
最新发布
07-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值