关于php:使用OpenRestyLua实现灰度测试金丝雀

3次阅读

共计 2352 个字符,预计需要花费 6 分钟才能阅读完成。

https://openresty.org/en/ 下载地址 如何装置部署不是本节内容

在理论我的项目中遇到重构或者新版本公布, 新老零碎如何高效的切换, 现目前的答案就是Gateway 网关, 有很多开源的网关Kong Apisix 然而这里来教如何本人实现一个 api 网关

介绍

openresty 基于 Nginx 开发 应用 Lua 让程序更加灵便, Lua基于 C 开发, 脚本语言 领有原生协程, 性能强 本人简略看一下 lua 的语法咱们就开始上手了

思路

网关实现思路其实很简略, 申请来到 openresty 而后通过 Lua 脚本解析相干 route/ queryParmes / Body 内容, 而后做出想要的后果, 比方我想要/abc 返回

{"msg": "helloworld"}

或者 GET 返回 1, POST 返回 2, 因为是 luaJit 耗时很低

代码

将通过 redis来实现拜访指定路由后申请新我的项目, 没有则拜访老我的项目

local re_uri = ngx.var.request_uri // 获取申请的 uri
local re_method = ngx.var.request_method // 获取申请的形式
if re_method == "GET" then // 这里判断如果是 get 申请就判断一下有没有传参 有传参就把前面的参数去掉 因为只须要保留 uri
    local cat_len = string.find(re_uri, "?")
    -- ngx.say(type(cat_len))
    if type(cat_len) == "number" and cat_len > 0 then
        re_uri = string.sub(re_uri, 0, cat_len-1)
    end
end
// 开始连贯 redis
local function close_redis(redis_instance)
    if not redis_instance then
        return
    end
    local ok,err = redis_instance:close();
    if not ok then
        ngx.say("close redis error :",err);
    end
end

-- 连贯 redis
local redis = require("resty.redis");
-- 创立 redis 对象
local redis_instance = redis:new();
redis_instance:set_timeout(1000)

local ok,err = redis_instance:connect('127.0.0.1',6379)
if not ok then
    ngx.say("connect redis error :",err)
    return close_redis(redis_instance);
end

--Redis 身份验证
local auth,err = redis_instance:auth(""); // 如果没有明码能够正文掉这一段代码 
if not auth then
    ngx.say("failed to authenticate :",err)
end

-- 连贯胜利
local resp,err = redis_instance:set("lua","hello world") // 连贯胜利写入一个 lua helloworld
if not resp then
    ngx.say("set msg error :",err)
    return close_redis(redis_instance)
end


-- 获取 API 是否存在 
local resp, err = redis_instance:get("gateway:"..re_uri)
if not resp then
    ngx.say("get msg error :", err)
    return close_redis(redis_instance)
end

// 如果不存在则拜访老我的项目
if resp == nil then
    ngx.exec("@old");
end
if resp == "1" then
    ngx.exec("@new"); // 如果存在则拜访新我的项目
else
    ngx.exec("@old");
end
close_redis(redis_instance) // 完结之后敞开 redis 连贯

配置 openresty

lua脚本写好之后须要在 openresty 配置加上, 因为是基于 nginx 开发的所以配置和 nginx 是差不多的

vim nginx.conf

location / { // 拜访路由则加载 lua 脚本
      add_header content-type application/json;
      content_by_lua_file /www/lua/gateway.lua;
    }
    
    location @old{ // 旧我的项目
      try_files $uri =404;
      fastcgi_pass  unix:/tmp/php-cgi-72.sock;
      fastcgi_index index.php;
      include fastcgi.conf;
      include pathinfo.conf;
    }
    
    location @new{ // 新我的项目
      proxy_http_version 1.1;
      proxy_set_header Connection "keep-alive";
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header REMOTE-HOST $remote_addr;
      proxy_pass http://127.0.0.1:13001;
    }

重载配置

openresty reload

完结

curl http://localhost/

hello OpenResty

本文由博客一文多发平台 OpenWrite 公布!

正文完
 0