Nginx常见分发算法实现
1、基于轮询分发:根据请求流量均匀分发到后端服务器
upstream web {
server server1;
server server2;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://web;
}
}
2、基于主备分发:默认分发到主,主宕机后分发到备
upstream web {
server server1;
server server2 backup;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://web;
}
}
3、基于权重:通过配置权重,可以让性能好的服务器承担更多的负载
upstream web {
# 设置权重比例1:2
server server1 weight=1;
server server2 weight=2;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://web;
}
}
4、基于ip_hash分发:保证来自同样源地址的请求都分发到同一台主机
upstream web {
ip_hash; # 指定ip_hash即可,默认weight权重比例1: 1
server server1;
server server2;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://web;
}
}
需要注意:ip_hash算法不支持backup、weight设置。默认权重为1
5、基于url的hash分发:不同的URL我去找不同的机器访问,就是把url计算出一个值然后除以机器的数量取余 ,需要安装第三方插件
插件安装步骤:在nginx分发器上,将nginx主程序包和下载好的第三方软件包放在同一个目录下解压,配置编译安装。
下面直接演示配置编译安装,下载和解压请自行解决。
1)解压后进入nginx目录
cd nginx-1.15.12/
2)配置
./configure --prefix=/usr/local/nginx --add-module=/root/ngx_http_consistent_hash-master
3)编译和安装
make & make install
4)编辑nginx配置文件
vim /usr/local/nginx/conf/nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream web {
consistent_hash $request_uri;
server server1 ;
server server2 ;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://web;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
5)重启nginx服务
systemctl restart nginx