Openresty+Redis實現灰度發佈

轉載自:https://www.cnblogs.com/ph7seven/p/9941189.html

一、架構

環境:

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

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章