openresty+lua 实现简单的灰度发布,openrestylua


openresty 是在nginx之上集成了lua模块的第三方服务器,我们很容易基于lua对openresy进行简单的二次开发。下面就是一个简单的openresty+lua 的灰度发布的测试demo,简单地来说就是通过client的ip来访问不同的服务器。

nginx.conf 配置文件如下:

upstream client1 {
		server 127.0.0.1:8080;

	}

	upstream client2 {
		server 127.0.0.1:8081;
	}

http {

server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
		default_type 'text/plain';

		location /test {
			content_by_lua_file /Users/chenguowei/local/openresty/nginx/lua_conf/huidu.lua;
		}

		location @client1 {
			proxy_pass http://client1;
		}

		location @client2 {
			proxy_pass http://client2;
		}
}

 

huidu.lua 文件如下:

local redis = require "resty.redis"
local cache = redis.new()
cache:set_timeout(60000)

local ok, err = cache.connect(cache, "127.0.0.1", 6379)
if not ok then
	ngx.say("failed to connect:", err)
	return
end

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 intercept = cache:get(local_ip)

if intercept == local_ip then
	ngx.exec("@client2")
	return
end

ngx.exec("@client1") --之前不能有任何的ngx.say()函数执行过,否则请求会出错

local ok, err = cache:close()

if not ok then
	ngx.say("failed to close: ", err)
	return
end

接下来使用如下命令来测试:

curl http://127.0.0.1/test

会请求 127.0.0.1:8080 服务器上的内容。

当你在 redis 内添加 set 127.0.0.1 127.0.0.1 这个键值,再次发送  curl http://127.0.0.1/test 会请求到127.0.0.1:8081 服务器上的内容。

相关内容

    暂无相关文章