upstream指令的参数
upstream myserver {server localhost:8001 down;server localhost:8002 backup;server localhost:8003 max_conns=200 max_fails=3 fail_timeout=10;
}
max_conns:限制最大同时连接数
down:服务不可用,禁止访问此服务
backup:备用机,只有在其他服务器无法访问的时候才能访问到,不适用于hash负载均衡、随机负载均衡
max_fails:表示失败几次,则标记此服务不可用,默认值1
fail_timeout:在fail_timeout设置的时间段内,请求失败max_fails次后标记此服务不可用。fail_timeout默认值10。
负载均衡策略
轮循
按先后顺序逐个转发到各个服务。
upstream myserver {server localhost:8001;server localhost:8002;server localhost:8003;
}
加权轮循
轮循upstream内的服务,按配置的权重比例分配请求。
upstream myserver {# weight设置权重server localhost:8001 weight=1;server localhost:8002 weight=5;server localhost:8003 weight=2;
}
ip哈希
根据客户端的ip地址计算出一个哈希值,根据哈希值不同将请求转发到不同的服务上,来自同一个ip的请求总是被分配到同一的服务上。
upstream myserver {ip_hash;server localhost:8001;server localhost:8002;server localhost:8003;
}
uri哈希
根据请求的uri计算哈希值,根据哈希值不同将请求转发到不同的服务上,相同uri的请求总是被分配到同一个服务上。
upstream myserver {hash $request_uri;server localhost:8001;server localhost:8002;server localhost:8003;
}
最少连接
将请求分配到连接最少的服务上。
upstream myserver {least_conn;server localhost:8001;server localhost:8002;server localhost:8003;
}
随机
将请求随机转发。upstream myserver {random;server localhost:8001;server localhost:8002;server localhost:8003; }
流量分配
Cookie
我们希望根据用户的身份来决定他们是否接入新版本。这时,可以通过浏览器的 Cookie 来实现基于用户的新版本发布。例如,我们在应用中设置了一个名为 is_v2 的 Cookie,标记用户是否参与新版本的新版本测试。
upstream v1server {server localhost:8001;
}
upstream v2server {server localhost:8101;
}
server {listen 80;server_name example.com;location / {if ($http_cookie ~* "is_v2=1") {proxy_pass http://v2server;}proxy_pass http://v1server;}
}
在上面的配置中,如果用户的 Cookie 中有 is_v2=1 的标记,Nginx 会将该用户的请求路由到新版本的服务(localhost:8101);否则,用户的请求会继续访问旧版本的服务(localhost:8001)。这种方式适合用于定向测试和用户分组。
请求头
根据请求中的用户 ID 判断是否将请求路由到新版本环境。这可以通过 Nginx 的 Lua 模块和 Redis 来实现。
upstream v1server {server localhost:8001;
}
upstream v2server {server localhost:8101;
}
server {listen 80;server_name example.com;location / {access_by_lua_block {local redis = require "resty.redis"local red = redis:new()local ok, err = red:connect("redis_host", redis_port)if not ok thenngx.log(ngx.ERR, "failed to connect to Redis: ", err)ngx.exit(500)endlocal user_id = ngx.req.get_headers()["X-User-ID"]local is_v2 = red:get("v2:" .. user_id)if is_v2 == "1" thenngx.var.upstream = "v2server"end}proxy_pass http://v1server;}
}
在上面的示例中,我们连接到 Redis,并根据请求中的用户 ID 判断是否将请求路由到新版本环境。ngx.var.upstream 变量用于动态设置上游地址,从而实现新版本环境的路由。
请求参数
根据请求中的某个参数值决定路由到哪个版本。
upstream myserver {server localhost:8000;
}
upstream v1server {server localhost:8001;
}
upstream v2server {server localhost:8101;
}
server {listen 80;server_name example.com;location / {set $group "myserver";if ($query_string ~* "isv2=1") {set $group v2server;}if ($query_string ~* "isv2=0") {set $group v1server;}proxy_pass http://$group;}
}
在上面的配置中,我们根据请求参数 isv2 的值来决定路由到哪个版本。如果参数值为 1,则路由到v2版本;如果参数值为 0,则路由到v1版本,默认路由到默认服务。
来源:https://www.iwmyx.cn/nginxfzjhpz.html