nginx 负载均衡的几种方式 桃扇骨 2022-04-05 08:09 177阅读 0赞 > 看nginx文档:[http://nginx.org/en/docs/http/load\_balancing.html][http_nginx.org_en_docs_http_load_balancing.html] 提到负载均衡的几种方式,简单翻译记录一下,以备不时之需。 ### 负载均衡机制 ### nginx提供如下几种负载均衡机制(或方式): 1. 循环机制 – 循环分发对应用服务器的请求 2. 最少连接机制 – 将请求发送给连接数最少的服务器 3. ip-hash机制 – 哈西函数用于确定请求被配那个服务器(基于客户端IP地址) #### 默认的负载均衡配置 #### 最简单的nginx负载均衡配置如下: > http \{ > upstream myapp1 \{ > server [srv1.example.com][]; > server [srv2.example.com][]; > server [srv3.example.com][]; > \} > server \{ > listen 80; > location / \{ > proxy\_pass [http://myapp1][http_myapp1]; > \} > \} > \} 上例中的同一应用的三个实例运行在srv1-srv3,当负载均衡没有特别配置,则默认循环机制。所以请求代理至服务器组myapp1,然后nginx应用HTTP负载均衡分发请求。 nginx中的反向代理实现了对HTTPS、HTTPS、FastCGI、uwsgi、SCGI、memcached的负载均衡。 设置FastCGI、uwsgi、SCGI、memcached的负载均衡使用相应的 fastcgi\_pass、 uwsgi\_pass,、scgi\_pass、 memcached\_pass 指令即可。 #### 最少连接机制 #### 另一种负载均衡原则是最少连接机制。当某些请求耗费较长时间完成时,最少连接机制能让实例的负载更加均衡。 在最少连接机制下nginx不会让大量请求使应用服务器超载,而是将请求分发至相对“悠闲”的服务器。 当least\_conn指令用在服务器组配置中时,最少连接机制就生效了。 > upstream myapp1 \{ > least\_conn; > server [srv1.example.com][]; > server [srv2.example.com][]; > server [srv3.example.com][]; > \} #### 会话持久 #### 请注意循环或者最少连接数负载均衡机制,可能将同一客户端的请求分发至不同的服务器,无法保证相同客户端的请求总是会被指向相同服务器。 如果需要将客户端与服务端绑定,换而言之:为了使客户端请求总是分发向特定的服务器,ip-hash负载均衡机制就派上了用场。 使用ip-hash客户端IP地址作为一个hash运算的key,以此决定服务器组中的哪台服务器处理客户端请求。该方法保证来自相同客户端的请求总是指向相同服务器,除非服务器不可用。 配置ip-hash负载均衡只需要将ip\_hash指令加入服务器组配置中: > upstream myapp1 \{ > ip\_hash; > server [srv1.example.com][]; > server [srv2.example.com][]; > server [srv3.example.com][]; > \} #### 加权负载均衡 #### 使用服务器权重可进一步影响nginx负载均衡。 上面的例子中,服务器权重没有配置,意味着所有服务器等权重的应用于负载均衡。 循环机制下大量请求以统一的方式处理,各服务器基本会被分发数量相等的请求。 当权重参数指定给服务器,权重就作为负载均衡的决定条件。 > upstream myapp1 \{ > server [srv1.example.com][] weight=3; > server [srv2.example.com][]; > server [srv3.example.com][]; > \} 在上面的配置中每5个请求,3个会被指向srv1,1个指向srv2,1个指向srv3。 在最新版本的nginx中权重可以和最少连接以及ip-hash负载均衡使用。 转自:[https://blog.csdn.net/xiojing825/article/details/78802154][https_blog.csdn.net_xiojing825_article_details_78802154] [http_nginx.org_en_docs_http_load_balancing.html]: http://nginx.org/en/docs/http/load_balancing.html [srv1.example.com]: http://srv1.example.com [srv2.example.com]: http://srv2.example.com [srv3.example.com]: http://srv3.example.com [http_myapp1]: http://myapp1 [https_blog.csdn.net_xiojing825_article_details_78802154]: https://blog.csdn.net/xiojing825/article/details/78802154
还没有评论,来说两句吧...