[Linux] Nginx_Lua_模块开发,linuxnginx_lua
[Linux] Nginx_Lua_模块开发,linuxnginx_lua
1. 安装openresty http://openresty.org/ 查看最新版
apt-get install libreadline-dev libpcre3-dev libssl-dev perl
cd /home/download;
wget http://agentzh.org/misc/nginx/ngx_openresty-1.0.10.44.tar.gz
tar xzvf ngx_openresty-1.0.10.44.tar.gz
cd ngx_openresty-1.0.10.44;
./configure --with-luajit --prefix=/home/server/openresty
make; make install
2. 修改nginx配置文件
http {
server {
listen 8080;
location ~ ^/data/feed/(.*) {
default_type text/plain;
set $api_keys $1;
set $api_response_template "_callback({__template__});";
content_by_lua_file conf/nginx_redis_module.lua;
}
location /redis_get {
# internal;
set_unescape_uri $key $arg_key;
redis2_query get $key;
redis2_pass 127.0.0.1:9211;
}
}
}
3. 编写nginx_redis_module.lua脚本
local parser = require "redis.parser"
function main()
local api_keys = ngx.var.api_keys
local resp_template = ngx.var.api_response_template
local api_vals = getApiVals(api_keys)
ngx.say(composeResponseTemplate(resp_template, api_vals))
end
function split(inputstr, sep)
ret={} ; i=1
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
ret[i] = str
i = i + 1
end
return ret
end
function getRedisVal(reply)
local ret, type = parser.parse_reply(reply)
if type == parser.BAD_REPLY then
ngx.log(ngx.ERR, "NGX_REDIS_LUA_EXCEPTION: BAD REPLY, textual error message from the redis parser!")
elseif type == parser.ERROR_REPLY then
ngx.log(ngx.ERR, "NGX_REDIS_LUA_EXCEPTION: ERROR_REPLY, error message from the redis server!")
else
return ret
end
end
function getApiVals(api_keys)
local vals = {}
local redis_reqs = {}
for api_key in string.gmatch(api_keys, "([^,]+)") do
table.insert(redis_reqs, {"/redis_get", { args = {key=api_key} } })
end
local resps = { ngx.location.capture_multi(redis_reqs) }
for i, resp in ipairs(resps) do
table.insert(vals, getRedisVal(resp.body))
end
return vals
end
function composeResponseTemplate(template, api_vals)
local combinedValue = http://hi.baidu.com/leonchunlai/blog/item/table.concat(api_vals, ", ")
local replacedTemplate, count = string.gsub(template, "__template__", combinedValue)
return replacedTemplate
end
main()
4. 测试效果,从redis读出name和age的值
curl localhost:8080/data/feed/name,age
_callback({leonchunlai, 99});
评论暂时关闭