如題,本文是筆者使用openresty 和lua腳本實現的簡單灰度發佈系統,記錄下來。html
1、安裝nginx
參考openresty 官方網站安裝openresty便可dom
建議參考文章https://www.cnblogs.com/zdz8207/p/Nginx-Lua-OpenResty.html網站
1.下載軟件包lua
wget https://openresty.org/download/openresty-1.13.6.2.tar.gzurl
2.解壓spa
tar zxcf openresty-1.13.6.2.tar.gz.net
cd openresty-1.13.6.2/插件
進入插件目錄cd bundle/rest
3.安裝LuaJIT
cd LuaJIT-2.1-20180420/
make clean && make && make install
ln -sf luajit-2.1.0-alpha /usr/local/bin/luajit
4.安裝ngx_openresty、(ngx_cache_purge、nginx_upstream_check_module安裝參考上面的url)
root@user:/usr/servers/ngx_openresty-1.9.7.1/bundle# cd ..
root@user:/usr/servers/ngx_openresty-1.9.7.1# ./configure --prefix=/usr/servers --with-http_realip_module --with-pcre --with-luajit --add-module=./bundle/ngx_cache_purge-2.3/ --add-module=./bundle/nginx_upstream_check_module-0.3.0/ -j2
root@user:/usr/servers/ngx_openresty-1.9.7.1# make && make install
2、安裝好之後直接就能夠配置實踐了,openresty將lua都集成好了,nginx配置文件無需特殊聲明引入lua file。
1.nginx.conf 添加兩個灰度發佈的環境 #grey 灰度環境地址 #prd生產環境地址
upstream grey {
server 127.0.0.1:8080;
}
upstream prd {
server 139.162.116.84:8080;
}
添加對應location
location @grey{
proxy_pass http://grey
}
location @prd{
proxy_pass http://prd
}
在server 里根location指定lua文件
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
default_type 'text/html';
content_by_lua_file /root/openresty/nginx/conf/lua_conf/grey.lua;
}
[root@luka77 ~]# cd openresty/nginx/conf/lua_conf/
[root@luka77 lua_conf]# ls
grey.lua
[root@luka77 lua_conf]# cat grey.lua
foreign_env = 'grey'
china_env = 'prd'
abtest_num = 50 流量比率
local num = math.random(100);
if (num <= abtest_num) then
ngx.log(ngx.INFO,'use foreign environment',foreign_env)
ngx.exec("@"..foreign_env)
else
ngx.log(ngx.INFO,'use foreign environment',china_env)
ngx.exec("@"..china_env)
end
[root@luka77 lua_conf]#
目前實現的是一個按照流量百分比控制的灰度分流控制~
abtest_num 爲流量比率