Nginx负载均衡
官方doc
1.Nginx提供了3种负载均衡策略:
1)、round-robin 轮询=>采用轮询机制
2)、least-connected=>下次的请求总会分配给连接数最小的server
3)、 ip-hash=>根据客户端的ip在较长的一段时间内为客户端分配固定的后台server
Nginx默认的负载均衡策略是round-robin轮询机制
2.example
http {
//配置相同应用服务器的地址
upstream myapp1 {
server srv1.example.com;
server srv2.example.com;
server srv3.example.com;
}
//Nginx的80端口用负载均衡替换为上面upstream后的配置
server {
listen 80;
location / {
proxy_pass http://myapp1;
}
}
}
3.如果需要改为其他的配置
upstream myapp1 {
//在这里加上策略名即可
least_conn;
server srv1.example.com;
server srv2.example.com;
server srv3.example.com;
}
4.session持久化
upstream myapp1 {
ip_hash;
server srv1.example.com;
server srv2.example.com;
server srv3.example.com;
}
如果使用前面2种负载均衡策略,客户端发来的请求,每一次可能出现在不同的应用服务器上,如果我们需要把客户端跟某一台客户端绑一起,这个时候使用ip_hash的负载均衡即可
当我们的业务需求,需要长时间使用session,可以采用ip_hash这种负载均衡策略
5.负载均衡加权
还可以使用加权来配置负载均衡,如果不加,那么每一台都是同等情况下访问
upstream myapp1 {
server srv1.example.com weight=3;
server srv2.example.com;
server srv3.example.com;
}
每5次请求有3次会访问server1