负载均衡方案

97 阅读2分钟

负载均衡方案

选型

负载均衡一般分为硬件负载均衡和软件负载均衡,硬件一般使用F5 Network Big-IP也就是F5,但是硬件费用较高,软件方面可以使用LVS、Nginx、HAproxy和阿里云负载均衡SLB,结合费用与实际业务量,选择Nginx进行实现负载均衡;

准备工作

Docker、Nginx 1.16.1 1、获取Nginx官方程序 获取Nginx官方程序,目的程序中的配置文件,在使用Docker容器时,将本地配置文件,映射Docker容器中,便于配置;

配置Nginx

默认轮询

upstream node{
	server 10.26.24.75:9002 weight=2;
	server 10.26.24.75:9003 weight=2;
	server 10.26.24.75:9004 weight=1;
}

结合weight取其权重值,请求服务器时,则是按请求的次数进行轮询请求,基本以 9002、9003、9002、9003、9001,按照配置的权重进行分配请求服务器地址; 当其中一台服务器宕机时,宕机服务器不在接收请求;

固定IP

upstream node{
	server 10.26.24.75:9002 weight=2;
	server 10.26.24.75:9003 weight=2;
	server 10.26.24.75:9004 weight=1;
ip_hash;
}

固定IP根据每个请求访问IP的hash结果分配,每次请求固定在同一台服务器,适合使用session保存客户信息的项目;

按响应 fair

按后端服务器的响应时间来分配请求,响应时间短的优先分配。需要安装第三方扩展;

根据url分配服务器

根据访问的url的hash结果进行分配请求服务器。同样需要安装第三方扩展;

./configure: error: C compiler cc is not found
www.cnblogs.com/jpfss/p/969… blog.csdn.net/hfsu0419/ar… blog.51cto.com/jweiang/143… 详解 www.cnblogs.com/loong-hon/p…

详细配置

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    #gzip  on;

	upstream node{
        #调度算法
		#1.轮循(默认)(weight轮循权值)
		#2.ip_hash:根据每个请求访问IP的hash结果分配。(会话保持)
		#3.fair:根据后端服务器响应时间最短请求。(upstream_fair模块)
		#4.url_hash:根据访问的url的hash结果分配。(需hash软件包)
		#参数
		#weight 默认为1.weight越大,负载的权重就越大
		#down:表示不参与负载均衡
		#backup:备份服务器,其它所有的非backup机器down或者忙的时候,请求backup机器
		#max_fails:允许最大请求错误次数,允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误 
		#fail_timeout:请求失败后暂停服务时间 max_fails次失败后,暂停的时间
		ip_hash;
		server 10.26.24.75:9002 weight=2 max_fails=5 fail_timeout=30s;
		server 10.26.24.75:9003 weight=2 max_fails=5 fail_timeout=30s;
		server 10.26.24.75:9004 weight=1 max_fails=5 fail_timeout=30s;
	}
	
    server {
        listen       80;
        server_name  localhost;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;

        location / {
            #root   html;
            #index  index.html index.htm;
			proxy_pass http://node;
			#后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
			proxy_set_header Host $http_host; 
			proxy_set_header X-Real-IP $remote_addr;
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

			proxy_connect_timeout 30; #nginx跟后端服务器连接超时时间(代理连接超时)
			proxy_send_timeout 60; #后端服务器数据回传时间(代理发送超时)
			proxy_read_timeout 60; #连接成功后,后端服务器响应时间(代理接收超时)

			proxy_buffering on;
			proxy_buffer_size 32k;
			proxy_buffers 4 128k;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }  
    }
}

五、测试