效果如下:
http://lua.enjoy.com/redisSk?goodId=147369
做法如下:
redis_sk.lua 脚本如下:
local redis = require "resty.redis"
--打开redis连接
local function open_redis()
local red = redis:new()
red:set_timeout(1000) -- 超时时间1 second
local res = red:connect('192.168.42.101',6379)
if not res then
return nil
end
res = red:auth(123456) --密码校验
if not res then
return nil
end
red.close = close
return red
end
--关闭连接
local function close(self)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
if self.subscribed then
return nil, "subscribed state"
end
return sock:setkeepalive(10000, 50)
end
local key = 'name'
local val = "100"
local arg = ngx.req.get_uri_args() --取req里所有的参数
for k,v in pairs(arg) do
key = k
val = v
break;
end
local red = open_redis()
local goodIdKey = "good:"..val;
ngx.say("key","--",goodIdKey);
local value = red:decr(goodIdKey) --取值
--red:set(key,val) --设新值
--close(red)
--red:init_pipeline()
--value = red:decr(goodIdKey) --取值
-- value = red:get(key)
--red:set(key, val)
--red:commit_pipeline()
--返回值到页面
--ngx.say(key,"--",val)
if (value > 0)
then ngx.say(key,':',value)
else
ngx.say(key,':','no stock!')
end
lua.conf 如下:
server {
listen 80;
server_name lua.enjoy.com;
location /hello {
content_by_lua 'ngx.say("ha ha hello!")';
}
location /args {
content_by_lua_block{
ngx.say(ngx.var.arg_a);
ngx.say(ngx.var.arg_b);
}
}
location /args_read {
content_by_lua_file /etc/nginx/lua/lua_args.lua;
}
location /setfile{
set_by_lua_file $val "/etc/nginx/lua/set.lua" $arg_a $arg_b;
echo $val;
}
location /access {
access_by_lua_file "/etc/nginx/lua/access.lua";
echo "welcom $arg_name !";
}
location /filter {
echo 'hello jack!';
echo 'you are welcome!';
body_filter_by_lua_file /etc/nginx/lua/filter2.lua;
}
location ^~ /redisReq {
content_by_lua_file /etc/nginx/lua/redis.lua;
}
location ^~ /redisSk {
content_by_lua_file /etc/nginx/lua/redis_sk.lua;
}
location ^~ /redisSkRet {
set_by_lua_file $val '/etc/nginx/lua/ret.lua';
echo $val;
}
}
错误时,查看日志:
通过 rewrite_by_lua_file '/etc/nginx/lua/ret.lua';
ngx.var.backend="usg=1"; 设置返回值