最近接触到了mysql数据库的连接池,做个记录
使用openresty框架,实现语言为Lua
通过连接池获取连接
1 传入数据库配置
2 mysql:new()
3 connect 数据库
4 result处理,返回状态判断
function mysql_pool:get_connect(conf) --conf 为数据库的配置
if ngx.ctx[mysql_pool] then
return true, ngx.ctx[mysql_pool]
end
local client, errmsg = mysql:new()
if not client then
return false, "mysql.socket_failed: " .. (errmsg or "nil")
end
client:set_timeout(10000) --设置超时时间
local options = {
host = conf.db.HOST,
port = conf.db.PORT,
user = conf.db.USER,
password = conf.db.PASSWORD,
database = conf.db.DATABASE
}
local result, errmsg, errno, sqlstate = client:connect(options)
if not result then
return false, "mysql.cant_connect: " .. (errmsg o