nginx lua读redis

  • 国内企业使用nginx的还是挺多的,我在工作的过程中,也经常使用nginx;下面就简单记录一下lua访问redis
    local cjson = require "cjson"
    local redis = require "resty.redis"
    local red = redis:new()  
    
    -- 设置后续操作的超时(以毫秒为单位)保护,包括connect方法
    red:set_timeout(60000) 
    -- 连接redis;两个参数分别是IP以及端口号
    local ok, err = red:connect("xxx.xxx.xxx.xxx", 6379) 
    if not ok then
        return
    end
    -- 设置连接密码
    red:auth("xxxx")
    -- 切换数据库,不设置,默认是0库
    red:select(1)
    
    local json_results={}
    
    local request_method = ngx.var.request_method
    if request_method == "GET" then
        json_results["userTag"] = 0
        local value = cjson.encode(json_results)
        ngx.say(value) 
        return
    elseif request_method == "POST" then
        ngx.req.read_body()
        args= ngx.req.get_body_data()
    end
    
    local arg=cjson.decode(args)
    
    if (type(arg["userIdList"]) == "nil") or (arg["userIdList"] == "") then 
        json_results["userTag"] = 0
        local value = cjson.encode(json_results)
        ngx.say(value) 
        return
    end
    
    local useridList = {}
    -- 设置为pipeline()模式;批量获取value
    red:init_pipeline()
    for k,userid in pairs(arg["userIdList"]) do
        useridList[k] = userid
        red:get("userTest_"..userid)
    end
    -- 提交所有的key
    local respTable, err = red:commit_pipeline()  
    
    -- local res, err = red:get(userid) 或者这种一次获得一个key
    
    if (not respTable) or  respTable == ngx.null then
        json_results["userTag"] = 0
        local value = cjson.encode(json_results)
        ngx.say(value) 
        return
    end
    
    local i = 0
    local res_userid={}
    -- 对有值的key的处理
    for k, v in pairs(respTable) do  
         if v ~= ngx.null then 
            res_userid[#res_userid+1] = cjson.decode(v)
            table.remove(useridList,k-i)
            i = i + 1
         end
    end 
    -- 对无值的key的处理
    for k,userid in pairs(useridList) do
        local k_v={}
        k_v["error_code"] = 101
        k_v["userid"] = userid
        res_userid[#res_userid+1] = k_v
    end
    
    json_results["userTag"] = res_userid
    local value = cjson.encode(json_results)
    ngx.say(value) 
    red:close()

     

你可能感兴趣的:(nginx lua读redis)