灰度发布大概原理以及nginx配置
1. 服务器划分
服务器类型 |
服务器主机编号 |
nginx 反向代理 |
A |
2.0版本api的服务器 |
B |
1.11版本api的服务器 |
C |
2.【反向代理主机】nginx.conf
1. nginx.conf 完整代码
- 1)将http请求直接交给lua文件封装的nginx.conf逻辑处理
- 2)定义好不同版本的后台url入口
server
{
listen 80;
server_name localhost;
####################【lua处理】####################
## 1、将对localhost访问由/opt/app/lua/dep.lua进行处理
## 2、根据逻辑处理后,决定回调如下两个其中1个内部跳转
location /
{
default_type "text/html";
content_by_lua_file /opt/app/lua/dep.lua; # 指定由lua文件处理http请求
#add_after_body "$http_x_forwarded_for";
}
################【nginx内部跳转1】#################
# 2.0版本的请求转发
location @server_version_2_0
{
proxy_pass 服务器A:9090; # 请求转发到2.0版本api的服务器A
}
################【nginx内部跳转2】#################
# 1.11版本的请求转发
location @server_version_1_11
{
proxy_pass 服务器B:8080; # 请求转发到1.11版本api的服务器B
}
error_page 500 502 503 504 404 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
2. 将location处理交给lua文件
location /
{
default_type "text/html";
content_by_lua_file /opt/app/lua/dep.lua; # 指定由lua文件处理http请求
#add_after_body "$http_x_forwarded_for";
}
3. 回调执行2.0版本的跳转
location @server_version_2_0
{
proxy_pass 服务器A:9090; # 请求转发到2.0版本api的服务器A
}
4. 回调执行1.11版本的跳转
location @server_version_1_11
{
proxy_pass 服务器B:8080; # 请求转发到1.11版本api的服务器B
}
3.【反向代理主机】dep.lua
1. lua 源文件
- 1)处理网络请求
- 2)对比ip地址,然后转发到对应的服务器
-- 1. 获取客户端请求的ip网络地址
clientIP = ngx.req.get_headers()["X-Real-IP"]
if clientIP == nil then
clientIP = ngx.req.get_headers()["x_forwarded_for"]
end
if clientIP == nil then
clientIP = ngx.var.remote_addr
end
-- 2. 连接到的memcached数据库服务
local memcached = require "resty.memcached"
local memc, err = memcached:new()
if not memc then
ngx.say("failed to instantiate memc: ", err)
return
end
local ok, err = memc:connect("127.0.0.1", 11211)
if not ok then
ngx.say("failed to connect: ", err)
return
end
-- 3. 从memcached数据库查询ip,是否存在对应的记录
local res, flags, err = memc:get(clientIP)
ngx.say("value key: ",res,clientIP)
if err then
ngx.say("failed to get clientIP ", err)
return
end
-- 4. 如果memcached数据库存在对应ip记录,则新的后台api版本对应的服务器url
if res == "1" then
ngx.exec("@server_version_2_0") # 匹配 location @server_version_2_0
return
end
-- 5. 反之走老的后台api对应的服务器url
ngx.exec("@server_version_1_11") # 匹配 location @server_version_1_11
- 1)获取到请求的【原始ip地址】
- 2)链接到数据服务器,查询ip地址是否在其中
- 3)根据在不在,走不同的nginx内部跳转
2. 转发到 2.0 版本的服务器
ngx.exec("@server_version_2_0") # 匹配 location @server_version_2_0
3. 转发到 1.11 版本的服务器
ngx.exec("@server_version_1_11") # 匹配 location @server_version_1_11
网友评论