zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

Nginx Lua Redis 实现灰度发布

RedisNginx 实现 发布 lua 灰度
2023-09-14 09:16:40 时间

1、安装

https://blog.csdn.net/mshxuyi/article/details/109106104 

2、用docker 启动 2个 nginx容器

[root@node3 conf]# docker ps
CONTAINER ID        IMAGE               COMMAND                   PORTS                NAMES
b040478a0ab9        nginx               "/docker-entrypoint.…"    0.0.0.0:82->80/tcp   nginx82
95a82189cc81        nginx               "/docker-entrypoint.…"    0.0.0.0:81->80/tcp   nginx

3、访问  nginx 容器 prd 生产环境

访问 nginx82 容器 pre-prd 预发布环境

4、配置 nginx

http {
    include       mime.types;
    default_type  application/octet-stream;
    lua_package_path "/usr/local/nginx/lua/redis.lua";    
    
    ...

    upstream prd {
        server   192.168.2.103:81;
    }

    upstream pre-prd {
        server   192.168.2.103:82;
    }

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;


        location / {
            default_type 'text/html';
            content_by_lua_file /usr/local/nginx/conf/conf.d/gray.lua;
        }

        location @prd {
            proxy_pass http://prd;
        }

        location @pre-prd {
            proxy_pass http://pre-prd;
        }

    ...

 5、创建 lua 脚本 

vim /usr/local/nginx/conf/conf.d/gray.lua

# 脚本
local redis = require "resty.redis"
local cache = redis.new()
cache:set_timeout(60000)

local ok, err = cache.connect(cache, '127.0.0.1', 6379)
if not ok then
   ngx.exec("@prd")
   return
end

local local_ip = ngx.req.get_headers()["X-Real-IP"]
if local_ip == nil then
        local_ip = ngx.req.get_headers()["x_forwarded_for"]
end

if local_ip == nil then
        local_ip = ngx.var.remote_addr
end

-- 在 redis 中根据客户端 ip 获取是否存在值
local res, err = cache:get(local_ip)

-- 如果存在则转发到 @pre-prd
if res == "1" then
        ngx.exec("@pre-prd")
        return
end

-- 如果不存在,则转发到 @prd
ngx.exec("@prd")

local ok, err = cache:close()
if not ok then
    ngx.say("failed to close:", err)
    return
end

6、重启

nginx -t 
nginx -s reload

7、测试

(1)现在 redis 里面还没有值,第一次访问,成功显示 prd 生产环境

(2)往 redis 插入 值,我本机 IP 为 192.168.2.199

(3)再次访问,成功显示 pre-prd 预发环境