秒杀系统之站点层 nginx中lua+redis抢购秒杀

效果如下:

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"; 设置返回值

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值