ngx_lua调用mysql

ngx_lua调用mysql

auth yufei
2016-07-21
ngx_lua调用mysql
来源于春哥的开源https://github.com/openresty/lua-resty-mysql

function F.check_session()
    local uid = args["uid"]
    local session = args["session"]
    local mysql = require "mysql"

    if uid == nil or uid == 0 then
        ngx.exit(403)
    end

    local db, err = mysql:new()
    if not db then
        ngx.say("failed to instantiate mysql: ", err)
        return
    end
    db:set_timeout(1000) -- 1 sec

    local ok, err, errno, sqlstate = db:connect{
        host = "bj020.mysql.goodid.com",
        port = 3306,
        database = "wk_im",
        user = "file6",
        password = "A37].j[M6SA_1",
        max_packet_size = 1024 * 1024
    }

    if not ok then
        ngx.header["ID_Error"] = "failed to connect: ", err, ": ", errno, " ", sqlstate
    ngx.exit(403)
        return
    end

    sql = "SELECT * FROM `sessions` WHERE `uid` =  ".. uid .. " and `session` = " .."\"" .. session .."\""
    res, err, errno, sqlstate = db:query(sql)
    if not res then
        ngx.header["ID_Error"] = "sql error"
        ngx.exit(403)
    elseif #(res) > 0 then
        --local cjson = require "cjson"
        local time_now = os.time()
        local last_time = tonumber(res[1]["last_activity"]) + tonumber(res[1]["life_time"])

        if last_time <= time_now then
        ngx.header["ID_Error"] = "session not at life_time"
        --暂时不判断session过期时间
            --ngx.exit(403)
        end

    else
        ngx.header["ID_Error"] = "sqldate error"
        ngx.exit(403)
    end
end

你可能感兴趣的:(MYSQL,LUA,NGINX)