负载均衡的分发方式
-
轮询机制
-
最少连接机制
-
ip-hash 机制
轮询机制-按照权重轮询
最简单的负载均衡配置如下:
http {
upstream myapp1 {
server srv1.example.com;
server srv2.example.com;
server srv3.example.com;
}
server {
listen 80;
location / {
proxy_pass http://myapp1;
}
}
}
我们还可以使用 weight 指定各个应用服务器接受分发请求的权重。像这样:
upstream myapp1 {
server srv1.example.com weight=3;
server srv2.example.com;
server srv3.example.com;
}
最少连接机制
这种负载均衡机制下,Nginx 会检测、并将请求分发给负载最低的服务器。
要使用这种机制,使用 least_conn :
upstream myapp1 {
least_conn;
server srv1.example.com;
server srv2.example.com;
server srv3.example.com;
}
ip-hash 机制
在轮询机制和最少连接机制下,Nginx 没法保证一个客户端的每次请求都连接到同一个服务器。如果想要保证每次客户端的请求都连接到一个业务服务器,可以使用 Nginx 提供的 ip-hash 负载均衡机制。
使用 ip-hash ,Nginx 会保证同一个 ip 的客户端每次请求都会连接到相同的业务服务器。
我们可以使用 ip_hash 配置:
upstream myapp1 {
ip_hash;
server srv1.example.com;
server srv2.example.com;
server srv3.example.com;
}