nginx - lua 作数据库连接池

local mysql = require ("resty.mysql")
local cjson = require ("cjson")

local pool = {}

local config = {
    host = "10.10.12.51",
    port = 3306,
    database= "xcwork",
    user = "root",
    password = "xuzhi",
    max_package_size = 1024*1024
}

function pool:getConnect()
    
    if ngx.ctx[pool] then
        ngx.say("直接从连接池中取Connection.")
        return true, ngx.ctx[pool]
    end    
        
    local dataBase, errmsg = mysql:new()
    
    if not dataBase then
        ngx.say("initail mysql connection : ") 
        ngx.say(errmsg)
        return nil
    end
    
    -- 10秒
    dataBase:set_timeout(10000)
    
    local result, errmsg, errno, sqlstate = dataBase:connect(config)
    
    if not result then
        ngx.say("host mysql connect failed.")
        return false, nil
    end
    
    ngx.ctx[pool] = dataBase
    return true, ngx.ctx[pool]
end


function pool:close() 
    if ngx.ctx[pool] then
        ngx.ctx[pool]:set_keepalive(60000, 100)
        ngx.ctx[pool] = nil
    end
end

function pool:query(sql)
    local ret, client = self.getConnect()
    
    if not ret then 
        ngx.say("get connect failure")
        return false, nil
    end
    
    local result, err, errno, sqlstate = client:query(sql)
    
    -- 放入连接池
    self.close()
    
    if not result then 
        ngx.say("execute sql failed")
        return false, nil
    end
    
    return true, cjson.encode(result)
end    
    
return pool

--------------------------------------------------   nginx 执行lua脚本  ----------------------------------------------------

local pool = require ("luascript.sql_pool")

local id = ngx.req.get_uri_args()["id"] or ""

local sql_query = "select userid, usercode, username, mobile, email, address, createdTime from userinfo where userid = " .. id

local ret, result = pool:query(sql_query)

if not ret then 
    ngx.say("未查询到数据")
    return nil 
end

ngx.say(result)  -- [[ 返回查询结果 ]]--

    
    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值