Nginx配置负载均衡

#)当前端请求后台,nginx反向代理到后台,配置负载均衡。#######################################################################

当后台服务器访问量比较大时,可以同一个服务部署多个。对应同一个前端web服务器。即,一个Nginx对应同一个后台应用的多个服务。

比如,后台服务,启动了2个:

http://localhost:8081/studydemo/  和  http://localhost:8082/studydemo/

项目中写测试方法如下:

 1 import lombok.extern.slf4j.Slf4j;
 2 import org.springframework.beans.factory.annotation.Value;
 3 import org.springframework.web.bind.annotation.GetMapping;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.bind.annotation.RestController;
 6 
 7 /**
 8  * 测试Nginx负载均衡
 9  * @Author HuXiaoxiao
10  */
11 @Slf4j
12 @RestController
13 @RequestMapping("/balance")
14 public class BalanceController {
15 
16     @Value("${server.port}")
17     private String port;
18 
19     @GetMapping("/test")
20     public String query() {
21         System.out.println("-------------------result:"+port);
22         return "SUCCESS";
23     }
24 
25 }

Nginx配置nginx.conf文件:

http {
    #配置nginx负载均衡---后端服务器组
    upstream testBalance {  #testBalance为自定义的名称
	server localhost:8081 weight=3;  
	server localhost:8082;  #这里也可以加上后台项目的context-path上下文
    }

    server {
        listen       8090;
        server_name  localhost;

        #配置前端代码位置
        location / {
            root   E:localDeployceshidist;
            index  index.html index.htm;
        }

        #使用负载均衡:
        location /apis/ {
            proxy_pass http://testBalance/studydemo/;  #引用后端服务器组。/studydemo是后台项目的context-path上下文。可以在这里拼接,也可以在开头负载均衡的端口后面加上
        }

    }  
}

然后启动nginx,测试:

 此时观察后台console的打印新消息:

  

 可以看出,8081和8082被访问的几率是3:1。

 **)nginx负载均衡的分发策略-----------------------------------------------------------------------------------------------------------------------------------

nginx的负载均衡:当服务器组中的某一台机器挂掉的时候,会自动去掉它,根据剩余的服务器继续按照策略分发,服务和分发的过程不会被打断。当这台机器恢复正常使用时,会自动加入。

分发策略通常根据每台后台服务器的硬件性能(比如内存、CPU)来设置。性能好的服务器,可以配置权重多一点。

1)、轮询 ——1:1 轮流处理请求(默认)

      每个请求按时间顺序逐一分配到不同的应用服务器,如果应用服务器down掉,自动剔除,剩下的继续轮询。 
2)、权重 ——you can you up
      通过配置权重,指定轮询几率,权重和访问比率成正比,用于应用服务器性能不均的情况。 

  比如:

1 upstream testBalance {  
2     server localhost:8081 weight=3;  #权重是3
3     server localhost:8082;       #默认权重1
4 } 

3)、ip_哈希算法
      每个请求按访问ip的hash结果分配,这样每个访客固定访问一个应用服务器,可以解决session共享的问题。 

具体参考:https://www.cnblogs.com/1214804270hacker/p/9325150.html

#) Nginx服务器的负载均衡

原文地址:https://www.cnblogs.com/mySummer/p/11532395.html