【openresty】藍綠髮布(ip白名單)

• 什麼是藍綠髮布?html

1. 藍綠部署原理上很簡單,就是經過冗餘來解決問題。一般生產環境須要兩組配置(藍綠配置),一組是active的生產環境的配置(綠配置),一組是inactive的配置(藍配置)。
2. 當用戶訪問的時候,只會讓用戶訪問在綠色環境(active)的服務器集羣。在綠色環境(active)運行當前生產環境中的應用,也就是舊版本應用version1。當你想要升級到version2 ,在藍色環境(inactive)中進行操做,即部署新版本應用,並進行測試。若是測試沒問題,就能夠把負載均衡器/反向代理/路由指向藍色環境了。
3. 隨後須要監測新版本應用,也就是version2 是否有故障和異常。若是運行良好,就能夠刪除version1 使用的資源。若是運行出現了問題,能夠經過負載均衡器指向快速回滾到綠色環境。

• openresty+redis實現api接口簡單的藍綠髮布:nginx

1. 當用戶在發起請求後,判斷用戶當前的ip網絡,若是發現是屬ip白名單列表,則指向藍色環境;若不在ip白名單列表,則指向綠色環境。
2. 下面以"訂單中心接口"進行藍綠髮布,當請求匹配到`location /order_center`後,進過`gary_release.lua`文件處理,`gary_release.lua`文件會獲取該請求的用戶ip 和 redis中的ip白名單列表進行匹配,若是匹配成功會從新請求`location /gray_develop`這時候就會走藍色環境,不然就會走綠色環境

clipboard.png

【nginx.conf配置文件以下】:

http{
    upstream develop {
        server develop.banchengyun.com;
    }redis

    upstream online {
        server api.banchengyun.com;
    }api

...數組

server{
...服務器

    #灰度發佈
    location /order_center {
        lua_code_cache off;
        default_type text/html;
        content_by_lua_file $root/gary_release.lua;
    }網絡

    location /gray_develop {
        proxy_pass http://develop/bee/WW_verify_...;
    }負載均衡

    location /gray_online {
        proxy_pass http://online/;
    }測試

}
}ui

【gary_release.lua文件以下】:
local redis = require("resty.redis");

-- 建立一個redis對象實例。在失敗,返回nil和描述錯誤的字符串的狀況下
local redis_instance = redis:new();

--設置後續操做的超時(以毫秒爲單位)保護,包括connect方法
redis_instance:set_timeout(10000)

--創建鏈接
local ip = '127.0.0.1'
local port = 6379
--嘗試鏈接到redis服務器正在偵聽的遠程主機和端口
local ok,err = redis_instance:connect(ip,port)
if not ok then
        ngx.say("connect redis error : ",err)
        return err
end

--獲取請求ip
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

local_ip = '1.1.1.1'

redis_instance:select(2)
ip_lists = redis_instance:get('ip_lists')
ip_lists = {"1.1.1.1", "2.2.2.2"}

-- 不是數組則直接轉向生產環境
-- if(type(ip_lists) ~= table)
-- then
--    ngx.exec("/gray_online");
-- end

local hit_ip = false
for k,v in pairs(ip_lists) do
if v == local_ip then
    hit_ip = true
end
end

-- 判斷是否在白名單而後轉到對應服務
if hit_ip == true then
ngx.exec("/gray_develop");
else
ngx.exec("/gray_online");
end

local ok,err=redis_instance:close();

相關文章
相關標籤/搜索