環境:nginx
192.168.189.131:tomcat服務redis
192.168.189.132:tomcat服務tomcat
192.168.189.130:OpenResty服務、redis服務架構
流程:dom
請求到達openresty,openresty從redis獲取白名單,而後判斷請求地址是否再白名單,在白名單轉到192.168.189.132服務不然轉到192.168.189.131服務socket
在redis中動態設置白名單,實現服務切換oop
一、在openresty根目錄建立目錄gray(做爲工做空間),在gray目錄建立conf(存放nginx配置文件nginx.conf)、logs(存放日誌文件)、lua(存放lua腳本)ui
二、配置nginx.conflua
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;
}
}
}
三、配置gray.luaspa
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.一、設置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
四、啓動openresty
在openresty/nginx/sbin執行:./nginx -p /root/data/program/openresty/gray (-p表示指定空間)
五、演示效果:
訪問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