负载均衡

目的

  • 解决单个节点压力过大,造成 Web 服务响应过慢,严重的情况下导致服务瘫痪,无法正常提供服务。
  • 提升 Web 服务器响应性能

负载均衡常用的Web服务器软件

  • Nginx
  • HAProxy
  • LVS
  • Apache

Nginx 的内置负载均衡策略

Nginx负载均衡是通过upstream模块来实现,内置实现了三种负载策略。官网负载均衡配置说明:http://nginx.org/en/docs/http/load_balancing.html

  • 轮循(默认)

Nginx根据请求次数,将每个请求均匀分配到每台服务

  • 器最少连接

将请求分配给连接数最少的服务器。Nginx会统计哪些服务器的连接数最少。

  • IP Hash

绑定处理请求的服务器。第一次请求时,根据该客户端的IP算出一个HASH值,将请求分配到集群中的某一台服务器上。后面该客户端的所有请求,都将通过HASH算法,找到之前处理这台客户端请求的服务器,然后将请求交给它来处理。

以轮询负载策略为实例

  1. 如下为「轮询」配置文件 Nginx.conf:
# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 65535;
}

stream {

    log_format basic '$remote_addr [$time_local] '
                     '$protocol $status $bytes_sent $bytes_received '
                     '$session_time';

    upstream test_cluster {
         server 192.168.1.100:4010 weight=2 max_fails=3 fail_timeout=15;;
         server 192.168.1.101:4011 weight=3;
         server 192.168.1.102:4012 weight=1;
         server 192.168.1.103:4013 weight=4;
    }
   server {
      listen 50052;
      proxy_connect_timeout 1s;
      proxy_pass test_cluster;
      access_log  /var/log/nginx/test_cluster.log basic;
      error_log  /var/log/nginx/ptest_cluster-error.log debug;
    }

}
  1. 配置文件中参数说明:
  • proxy_pass test_cluster:表示将所有请求转发到 test_cluster 服务器组中配置的某一台服务器上
  • upstream模块:配置反向代理服务器组,Nginx会根据配置,将请求分发给组里的某一台服务器。test_cluster 是服务器组的名称。
  • upstream模块下的server指令:配置处理请求的服务器IP或域名,端口可选,不配置默认使用80端口。通过上面的配置,Nginx默认将请求依次分配给100,101,102来处理,可以通过修改下面这些参数来改变默认的分配策略:
    • weight

      默认为1,将请求平均分配给每台server,配置 weight 值,即配置分配请求权重

    • max_fails

      默认为1。某台Server允许请求失败的次数,超过最大次数后,在fail_timeout时间内,新的请求将不会分配给这台机器。如果设置为0,Nginx会将这台Server置为永久无效状态,然后将请求发给定义了proxy_next_upstream, fastcgi_next_upstream, uwsgi_next_upstream, scgi_next_upstream, and memcached_next_upstream指令来处理这次错误的请求

    • fail_timeout

      默认为10秒。某台Server达到max_fails次失败请求后,在fail_timeout期间内,nginx会认为这台Server暂时不可 用,不会将请求分配给它。(192.168.0.100这台机器,如果有3次请求失败,nginx在15秒内,不会将新的请求分配给它。)


参考资料:

原文地址:https://www.cnblogs.com/ronky/p/9792135.html