NGINX负载均衡策略

nginx:是一款轻量级的WEB服务器 / 反向代理服务器,占有内存小,并发力强。

作用:中间件 和 负载均衡

负载均衡几种策略:

  • 轮询(round-robin默认):每个请求按时间顺序逐一分配到不同的后端服务器,也是最简单的配置算法;如果后端服务器down掉,能自动剔除。
upstream [testround.com](http://testround.com/) 
{
    server 192.168.1.1:8080 ;
    server 192.168.1.2:8081 ;
    server 192.168.1.3:8082 ;
}
  • ip_hash:每个请求按访问IP的hash值结果进行分配,同一个IP客户端固定访问一个后端服务器。可以保证来自同一ip的请求被打到固定的机器上,可以解决session问题。如果后端服务器down掉,要手工down掉。
upstream [testiphash.com](http://testiphash.com/)
 {
    #后端服务器访问规则
    ip_hash;
    server 192.168.1.1:8080 ;
    server 192.168.1.2:8081 ;
    server 192.168.1.3:8082 ;
}
  • 权重算法:
    指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。weight的值越大分配到的访问概率越高,主要用于后端每台服务器性能不均衡的情况下,或者仅仅为在主从(2台服务器)的情况下设置不同的权值,达到合理有效的地利用主机资源。
upstream [testweight.com](http://testweight.com/) 
{
      #后端服务器访问规则
      server 192.168.1.1:8080 weight=2;
      server 192.168.1.2:8081 weight=2;
}
  • 最少连接(least_conn):把请求转发给连接数较少的后端服务器进行处理。例如Nginx负载中配置了两台服务器,sky和fans,当Nginx接收到一个请求时,sky正在处理的请求数是100,fans正在处理的请求数是200,则Nginx会把当前请求交给sky来处理。
upstream [testleastconn.com](http://testleastconn.com/)
 {
    least_conn;
    server 192.168.1.1:8080;
    server 192.168.1.2:8081;
}
server {
        listen 80;
        server_name localhost;
        
    location ^~ /round/ {
            proxy_pass http://testround.com;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_redirect off;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            client_max_body_size 8m;
            client_body_buffer_size 128k;
            proxy_connect_timeout 120;
            proxy_send_timeout 120;
            proxy_read_timeout 120;
            proxy_buffer_size 8k;
            proxy_buffers 4 32k;
            proxy_busy_buffers_size 64k;
            proxy_temp_file_write_size 64k;
        }
    location ^~ /iphash/ {
        proxy_pass http://testiphash.com;
    }
    location ^~ /weight/ {
        proxy_pass http://testweight.com;
    }
    location ^~ /leastconn/ {
          proxy_pass http://testleastconn.com;
    }
}   
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容