当前位置: 首页 > 工具软件 > Mobile Lua > 使用案例 >

nginx lua mysql 连接池_nginx - lua 作数据库连接池

柏正平
2023-12-01

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) -- [[ 返回查询结果 ]]--

 类似资料: