Rootop 服务器运维与web架构

基于openresty实现服务灰度发布

nginx配置文件:
# 定义3个upstream

upstream up1
{
	server 127.0.0.1:8001;
}

upstream up2
{
	server 127.0.0.2:8002;
}

upstream all
{
	ip_hash;
	server 127.0.0.1:8001;
	server 127.0.0.2:8002;
}

server
{
	server_name localhost;
	listen 80;

	# 请求交给lua脚本处理
	location /
	{
		lua_code_cache off;
		content_by_lua_file /mnt/proxy.lua;
	}

	# location @ 用于nginx内部跳转
	location @up1
	{
		proxy_pass http://up1;
	}

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

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

}

lua代码:

ngx.header.content_type="text/html;charset=utf8"
redis = require('resty.redis')
redis = redis.new()
redis:set_timeout(1000)

ok,err =  redis:connect('127.0.0.1', 6379)

if not ok then
	ngx.say('connect to redis failed ! reason: ' .. err)
end

-- 从redis中检查是否存在即将更新的upstream主机
check_up1 = redis:get('update1') --(up1)
check_up2 = redis:get('update2') --(up2)
redis:close()
-- 注意返回的数据类型来判断
if check_up1 == "1" then
	ngx.exec("@up2")
elseif check_up2 == "1" then
	ngx.exec("@up1")
else
	ngx.exec("@all")
end

原理就是利用redis中设置指定key,比如要更新主机1,则redis中添加key=update1,value=1,当浏览器请求进入nginx的content阶段后执行lua脚本,脚本中检查redis中是否存在要更新的主机,如果发现某个主机要更新则通过Nginx API for Lua中的ngx.exec接口内部跳转到另一台主机。
如果两个都不更新,则根据nginx自己的方式(默认轮询)分发请求。

nginx里使用了ip_hash保持会话,主要是为了用户的请求在后端记录的日志中保持完整。

原创文章,转载请注明。本文链接地址: https://www.rootop.org/pages/4175.html

作者:Venus

服务器运维与性能优化

评论已关闭。