• 什麼是藍綠髮布?
1. 藍綠部署原理上很簡單,就是通過冗餘來解決問題。通常生產環境需要兩組配置(藍綠配置),一組是active的生產環境的配置(綠配置),一組是inactive的配置(藍配置)。
2. 當用戶訪問的時候,只會讓用戶訪問在綠色環境(active)的服務器集羣。在綠色環境(active)運行當前生產環境中的應用,也就是舊版本應用version1。當你想要升級到version2 ,在藍色環境(inactive)中進行操作,即部署新版本應用,並進行測試。如果測試沒問題,就可以把負載均衡器/反向代理/路由指向藍色環境了。
3. 隨後需要監測新版本應用,也就是version2 是否有故障和異常。如果運行良好,就可以刪除version1 使用的資源。如果運行出現了問題,可以通過負載均衡器指向快速回滾到綠色環境。
• openresty+redis實現api接口簡單的藍綠髮布:
1. 當用戶在發起請求後,判斷用戶當前的ip網絡,如果發現是屬ip白名單列表,則指向藍色環境;若不在ip白名單列表,則指向綠色環境。
2. 下面以"訂單中心接口"進行藍綠髮布,當請求匹配到`location /order_center`後,進過`gary_release.lua`文件處理,`gary_release.lua`文件會獲取該請求的用戶ip 和 redis中的ip白名單列表進行匹配,如果匹配成功會重新請求`location /gray_develop`這時候就會走藍色環境,否則就會走綠色環境
【nginx.conf配置文件如下】:
http{
upstream develop {
server develop.banchengyun.com;
}
upstream online {
server api.banchengyun.com;
}
...
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/;
}
}
}
【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();