【Nginx】Nginx负载均衡

1.Nginx 负载均衡


  • 1.2 默认方式:轮询(round-robin)

    round-robin — requests to the application servers are distributed in a round-robin fashion,
    以循环模式分发对服务器的请求,写法如下:
    upstream 块,定义了一组服务,后边跟这一组服务的名称:myapp1
    不用特殊声明默认就是轮询方式。
    http {
          
          
    	# 一组服务
        upstream myapp1 {
          
          
            server srv1.example.com;
            server srv2.example.com;
            server srv3.example.com;
        }
    
        server {
          
          
            listen 80;
    
            location / {
          
          
                proxy_pass http://myapp1;
            }
        }
    }
    

  • 1.3 链接最少、空闲(least-connected)

    least-connected — next request is assigned to the server with the least number of active connections,
    下一次请求会被分配给有最少活动连接数的服务器。
    这里和默认写法的区别就是在upstream块的第一行,声明了其负载均衡的方式为 least_conn
    upstream myapp1 {
    
    
        least_conn;
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }
    ...

  • 1.4 会话持续,也叫ip 哈希(Session persistence)

    a hash-function is used to determine what server should be selected for the next request (based on the client’s IP address).
    会通过一个哈希方法、算法去决定哪一个服务会接受到下一个用户请求(算法基于用户的ip)。
    简单来讲就是会把相同的ip的请求(也就等同于同一用户的请求分发到同一个服务器,这样其服务器上保存的用户信息相关的session就可以复用,类似于持久化了用户的会话session)
    这里和默认写法的区别就是在upstream块的第一行,声明了其负载均衡的方式为 ip_hash
	upstream myapp1 {
    
    
	    ip_hash;
	    server srv1.example.com;
	    server srv2.example.com;
	    server srv3.example.com;
	}
    ...

  • 1.5 服务器权重(Weighted)

    这个很好理解,就是在不添加权重之前,每个服务器都是一视同仁,但添加权重后,权重多的服务器会被重用、也就是分配到更多的请求,前期是请求足够多。
    写法也比较简单,就是在服务器后边加上一个权重的参数 weight = x
    upstream myapp1 {
    
    
        server srv1.example.com weight=3;
        server srv2.example.com;
        server srv3.example.com;
    }
    ...

如上,每五个请求,就会有3个被打到第一个server,后边两个server各一个。

It is similarly possible to use weights with the least-connected and ip-hash load balancing in the recent versions of nginx.
官方:在最新的Nginx版本中,同样可以使用权重参数于 least-connected 和 ip-hash 上。

猜你喜欢

转载自blog.csdn.net/cjl836735455/article/details/131487195