Loading... # 负载均衡的集中方式介绍 #### 1、轮询 轮询方式是Nginx负载默认的方式,顾名思义,所有请求都按照时间顺序分配到不同的服务上,如果服务Down掉,可以自动剔除,如下配置后轮询8081服务和8082服务。 ``` upstream dalaoyang-server { server localhost:8081; server localhost:8082; } ``` #### 2、权重 指定每个服务的权重比例,weight和访问比率成正比,通常用于后端服务机器性能不统一,将性能好的分配权重高来发挥服务器最大性能,如下配置后8082服务的访问比率会是8081服务的二倍。 ``` upstream dalaoyang-server { server localhost:8081 weight=1; server localhost:8082 weight=2; } ``` #### 3、iphash 每个请求都根据访问ip的hash结果分配,经过这样的处理,每个访客固定访问一个后端服务,如下配置(ip_hash可以和weight配合使用)。 ``` upstream dalaoyang-server { ip_hash; server localhost:8081 weight=1; server localhost:8082 weight=2; } ``` #### 4、最少连接 将请求分配到连接数最少的服务上。 ``` upstream dalaoyang-server { least_conn; server localhost:8081 weight=1; server localhost:8082 weight=2; } ``` #### 5、fair 按后端服务器的响应时间来分配请求,响应时间短的优先分配。 ``` upstream dalaoyang-server { server localhost:8081 weight=1; server localhost:8082 weight=2; fair; } ``` #### Nginx配置 以轮询为例,如下是nginx.conf完整代码。 ``` worker_processes 1; events { worker_connections 1024; } http { upstream dmgls.com { server localhost:8081; server localhost:8082; } server { listen 8080; server_name localhost; location / { proxy_pass http://dmgls.com; proxy_redirect default; } } } ``` #### 二、在宝塔中配置负载均衡,点击网站--设置--配置文件 ``` upstream XXX.COM{ #XXX.COM更改为需要负载均衡的域名 #upstream参数配置主副服务器 ip_hash; #IP哈希值算法 server 127.0.0.2:80; #服务器1,IP替换为自己的服务器真实IP server 127.0.0.3:80 weight=2; #服务器2,权重为2 IP替换为自己的服务器真实IP server 127.0.0.4:80 backup;#备用服务器,上面两个服务器都宕机后启用这一台,IP替换为自己的服务器真实IP } #upstream参数是可以无限配置的,也就是说多域名的情况下一样可以使用负载均衡。 upstream XX1.COM{ #XX1.COM更改为需要负载均衡的域名 #upstream参数配置主副服务器 ip_hash; #IP哈希值算法 server 127.0.0.2:80; #服务器1 IP替换为自己的服务器真实IP server 127.0.0.3:80 weight=2; #服务器2,权重为2 IP替换为自己的服务器真实IP server 127.0.0.4:80 backup;#备用服务器,上面两个服务器都宕机后启用这一台 } server { listen 80; server_name XXX.COM;#此处为宝塔面板绑定域名后自动生成不用管 index index.php index.html index.htm default.php default.htm default.html; root /www/wwwroot/xxx.com; location / { proxy_pass http://$host; proxy_connect_timeout 2s; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } #SSL-START SSL相关配置,请勿删除或修改下一行带注释的404规则 #error_page 404/404.html; #SSL-END #引用重定向规则,注释后配置的重定向代理将无效 include /www/server/panel/vhost/nginx/redirect/xpdtv.top/*.conf; access_log /www/wwwlogs/xxx.com.log; error_log /www/wwwlogs/xxx.com.log; } ``` <hr class="content-copyright" style="margin-top:50px" /><blockquote class="content-copyright" style="font-style:normal"><p class="content-copyright">版权属于:大漠孤狼</p><p class="content-copyright">本文链接:<a class="content-copyright" href="https://www.dmgls.com/1277.html">https://www.dmgls.com/1277.html</a></p><p class="content-copyright">转载时须注明出处及本声明</p></blockquote> Last modification:December 14th, 2021 at 09:01 pm © 允许规范转载 Support 如果觉得我的文章对你有用,请随意赞赏 Appreciate the author