一、需求
项目中有这样一个接口:使用get或post方式支持单个或批量的手机号加解密。
使用Jmeter做性能测后发现,当批量加解密超过100个手机号时,吞吐量只有260左右【2颗E5CPU总计32核+128G DDR3】,所以我们想在nginx中通过lua实现如下功能:当手机号大于100个,用nginx-upstream-A,反之用nginx- upstream-B,A和B两者互不影响。
二、设计
三、配置及代码实现
1)server.conf
server { listen 80; server_name chow.com.cn; access_log /data/nginx/1.4.1/logs/chow/access.log main; set $target 'b.chow.com.cn'; #支持lua中获取request_body_data lua_need_request_body on; location / { #超时重试 proxy_connect_timeout 60; proxy_send_timeout 60; proxy_read_timeout 60; proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504; proxy_next_upstream_tries 2; rewrite_by_lua_file /usr/local/nginx/conf/lua/proxy_pass_choice.lua; proxy_pass http://$target/; } }
2)upstream.conf
upstream a.chow.com.cn{ server 127.0.0.1:10001 weight=60; server 127.0.0.1:11001 weight=60; }upstream b.chow.com.cn{ server 127.0.0.1:12001 weight=60; server 127.0.0.1:13001 weight=60; }
3)proxy_pass_choice.lua
local maxGetMethodUriArgsLength = 1024;local maxPostMethodUriArgsLength = 1024;local batchTarget = "a.chow.com.cn";function getStringLength(str) if str == nil then return 0; else return string.len(str); endendfunction setTarget() if (ngx.req.get_method() == "GET") then if (getStringLength(ngx.var.args) > maxGetMethodUriArgsLength) then ngx.var.target = batchTarget; end else if (getStringLength(ngx.req.get_body_data()) > maxPostMethodUriArgsLength) then ngx.var.target = batchTarget; end endendfunction exceptionHandle(err) ngx.log(ngx.ERR, err);end--添加异常处理xpcall(setTarget, exceptionHandle);