Openresty+redis實現灰度釋出
阿新 • • 發佈:2018-11-11
一、架構
環境:
192.168.189.131:tomcat服務
192.168.189.132:tomcat服務
192.168.189.130:OpenResty服務、redis服務
流程:
請求到達openresty,openresty從redis獲取白名單,然後判斷請求地址是否再白名單,在白名單轉到192.168.189.132服務否則轉到192.168.189.131服務
在redis中動態設定白名單,實現服務切換
二、配置(openresty、redis、tomcat安裝忽略)
1、在openresty根目錄建立目錄gray(作為工作空間),在gray目錄建立conf(存放nginx配置檔案nginx.conf)、logs(存放日誌檔案)、lua(存放lua指令碼)
2、配置nginx.conf
user root; worker_processes 1; error_log logs/error.log; events { worker_connections 1024; } http {
#新增;;標識預設路徑下的lualib lua_package_path "$prefix/lualib/?.lua;;"; lua_package_cpath "$prefix/lualib/?.so;;"; upstream prod1 { server 192.168.189.131:8080; } upstream prod2 { server 192.168.189.132:8080; } server { listen 80; server_name localhost; location / {
#為每個請求執行gray.lua指令碼 content_by_lua_file lua/gray.lua; } location @prod1 { proxy_pass http://prod1; } location @prod2 { proxy_pass http://prod2; } } }
3、配置gray.lua
local redis=require "resty.redis"; local red=redis:new(); red:set_timeout(1000); --redis連線 local ok,err=red:connect("192.168.189.130", 6379); if not ok then ngx.say("failed to connect redis ",err); return; 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=ngx.var.remote_addr;
--redis中獲取白名單 local ip_lists=red:get("gray");
--判斷是否在白名單然後轉到對應服務 if string.find(ip_lists,local_ip) == nil then ngx.exec("@prod1"); else ngx.exec("@prod2"); end local ok,err=red:close();
注意:
redis配置註釋掉bind 127.0.0.1、設定protected-mode 為no;否則通過lua連線redis出錯
#bind 127.0.0.1
# Protected mode is a layer of security protection, in order to avoid that
# Redis instances left open on the internet are accessed and exploited.
#
# When protected mode is on and if:
#
# 1) The server is not binding explicitly to a set of addresses using the
# "bind" directive.
# 2) No password is configured.
#
# The server only accepts connections from clients connecting from the
# IPv4 and IPv6 loopback addresses 127.0.0.1 and ::1, and from Unix domain
# sockets.
#
# By default protected mode is enabled. You should disable it only if
# you are sure you want clients from other hosts to connect to Redis
# even if no authentication is configured, nor a specific set of interfaces
# are explicitly listed using the "bind" directive.
protected-mode no
4、啟動openresty
在openresty/nginx/sbin執行:./nginx -p /root/data/program/openresty/gray (-p表示指定空間)
5、演示效果:
訪問192.168.189.131服務:
訪問192.168.189.132服務:
redis中白名單gray:
請求地址192.168.189.130不在白名單,因此lua指令碼執行@prod1,對應server 192.168.189.131:8080
redis設定白名單gray:
請求地址192.168.189.130在白名單,lua指令碼執行@prod2,對應server 192.168.189.132:8080