1.下载安装nginx服务器(win10/Linux同样适用)
2.两个以上服务的服务地址
轮询:
upstream my_server {server 192.168.0.101:8080 weight=1;server 192.168.0.168:8088 weight=1;server 192.168.0.128:8080 weight=1;}server {listen 7777;server_name localhost;#charset koi8-r;#access_log logs/host.access.log main;location / {proxy_pass http://my_server;proxy_set_header Host $host;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_connect_timeout 1;proxy_read_timeout 1;proxy_send_timeout 1;#root html;#index index.html index.htm;}
加权轮询:
upstream my_server {server 192.168.0.101:8080 weight=5;server 192.168.0.168:8088 weight=4;server 192.168.0.128:8080 weight=1;}server {listen 7777;server_name localhost;#charset koi8-r;#access_log logs/host.access.log main;location / {proxy_pass http://my_server;proxy_set_header Host $host;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_connect_timeout 1;proxy_read_timeout 1;proxy_send_timeout 1;#root html;#index index.html index.htm;}
IP Hash:
upstream my_server {server 192.168.0.101:8080;server 192.168.0.168:8088;server 192.168.0.128:8080;ip_hash;}server {listen 7777;server_name localhost;#charset koi8-r;#access_log logs/host.access.log main;location / {proxy_pass http://my_server;proxy_set_header Host $host;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_connect_timeout 1;proxy_read_timeout 1;proxy_send_timeout 1;#root html;#index index.html index.htm;}
配置完成后,必须重启nginx才生效。
举例:三台服务,出现1-2台宕机无法访问的情况,如果不进行一下配置,在请求过程中,可能会造成请求时间变长
proxy_connect_timeout 1;
proxy_read_timeout 1;
proxy_send_timeout 1;
proxy_connect_timeout这个参数是连接的超时时间。我设置成1,表示是1秒后超时会连接到另外一台服务器。
1、ip_hash
每个请求按访问IP的hash结果进行分配,这样每个访客就可以固定访问一个后端服务,一定程度上可以解决session问题;它会将主机的 $ip 哈希映射到一个随机的固定值,然后对 3 取模得到响应的端口序号;
2、weight
weight代表权重,默认为1,权重越高,被分配的客户端请求就会越多
3、fair(第三方)
按后端服务器的响应时间来分配请求,响应时间短的将会被优先分配
upstream my_server {server 192.168.0.101:8080;server 192.168.0.168:8088;server 192.168.0.128:8080;fair;
}
4、url_hash
按访问URL的hash结果分配。这样相同的url会被分配到同一个节点,主要为了提高缓存命中率。比如,为了提高访问性能,服务端有大量数据或者资源文件需要被缓存。使用这种策略,可以节省缓存空间,提高缓存命中率
upstream my_server {server 192.168.0.101:8080;server 192.168.0.168:8088;server 192.168.0.128:8080;hash &request_uri;
}
5、least_conn
按节点连接数分配,把请求优先分配给连接数少的节点。该策略主要为了解决,各个节点请求处理时间长短不一造成某些节点超负荷的情况。
upstream my_server {server 192.168.0.101:8080;server 192.168.0.168:8088;server 192.168.0.128:8080;least_conn;
}
大家根据自身情况选择!