背景
服务是采用nginx+lua实现的,在nginx的配置中存在多处(共20多处)正则判断,期望进行优化
location ~* /test.gif {
rewrite_by_lua_file 'lua/edit.lua';
if ($query_string ~* "pd=8(&|$)") {
set $req_host inner.a.com;
proxy_pass http://127.0.0.1:8481;
}
if ($query_string ~* "pd=3(&|$)") {
set $req_host inner.b.com;
proxy_pass http://127.0.0.1:8481;
}
if ($query_string ~* "ffs=.*(\{|%7B).*(%22|\")flag(%22|\")(:|%3A)(%22|\")?1(%22|\")+.*(\}|%7D)") {
set $req_host inner.c.com;
proxy_pass http://127.0.0.1:8481;
}
}
改进方法
1、在nginx中定义pd、flag字段用来存储pd、flag的值
set $pd 0;
set $flag 0;
2、在set_by_lua_file中使用正则进行提取pd、flag的值
set_by_lua_file:
local args = ngx.req.get_uri_args()
if args['action'] == 'test' then
ngx.var.pd = '1'
else
ngx.var.pd = '2'
end
local encodeRegex = "flow%22%3A%22([0-9]+)%22"
local normalRegex = 'flow":"([0-9]+)'
local str = 'logExtra=%7B%22st%22%3A%22other%22%2C%22rid%22%3A%22%22%2C%22pos%22%3A%220%22%2C%22flow%22%3A%2212%22%2C%22extra%22%3A%22%7B%7D%22%2C%22actionType%22%3A%22refresh_bottom%22%7D&r=l1562578644706'
local str1 = '&logExtra={"st":"other","rid":"","pos":"0","flow":"12","extra":"{}","actionType":"refresh_bottom"}&r=l1562578644706'
local normalFlow = ngx.re.match(str1, normalRegex)
local encodeFlow = ngx.re.match(str, encodeRegex)
if encodeFlow ~= nil and encodeFlow[1] ~= nil then
ngx.var.flag = encodeFlow[1]
end
if normalFlow ~= nil and normalFlow[1] ~= nil then
ngx.var.flag = normalFlow[1]
end
3、在test.gif中直接使用$pd $flag进行判断
nginx.conf
set $flag 0;
set $pd 0;
location / {
location /tcbox {
set_by_lua_file $a '/test/set.lua';
if ($flag = 1) {
content_by_lua_file '/test/caseone.lua';
}
if ($flag = 2) {
content_by_lua_file '/test/casetwo.lua';
}
}
}
本文介绍了一个服务优化方法,通过在nginx配置中使用set_by_lua_file进行正则提取,减少了20多处的正则判断,提高效率。优化步骤包括定义pd和flag字段,然后在lua脚本中进行正则处理,并在nginx配置中直接引用结果。
1163

被折叠的 条评论
为什么被折叠?



