ngx_lua调用mysql

14 篇文章 0 订阅
4 篇文章 0 订阅

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值