1. 程式人生 > 資料庫 >lua+redis搶購秒殺

lua+redis搶購秒殺

效果如下:

做法如下:

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;
   }

}