最近接触到了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 or "nil") .. ", errno:" .. (errno or "nil") .. ", sql_state:" .. (sqlstate or "nil")
end
local query = "SET NAMES " .. "utf8"
local result, errmsg, errno, sqlstate = client:query(query)
if not result then
return false, "mysql.query_failed: " .. (errmsg or "nil") .. ", errno:" .. (errno or "nil") .. ", sql_state:" .. (sqlstate or "nil")
end
ngx.ctx[mysql_pool] = client
-- 测试,验证连接池重复使用情况
--[[
local count, err = client:get_reused_times()
ngx.say("xxx reused times" .. count);
--]]
return true, ngx.ctx[mysql_pool]
end
关闭连接
连接池机制,不调用close,选择keepalive 确保性能。
在lua_code_cache 为 on 时生效
function mysql_pool:close()
if ngx.ctx[mysql_pool] then
ngx.ctx[mysql_pool]:set_keepalive(60000, 80)
ngx.ctx[mysql_pool] = nil
end
end
SQL查询
1 调取connect函数,传入配置进行连接
2 client:query 开始sql语句查询
3 errmsg 返回状态处理
function mysql_pool:query(sql, conf) --sql 传入sql语句 conf 数据库配置文件
local ret, client = self:get_connect(conf)
if not ret then
return false, client, nil
end
local result, errmsg, errno, sqlstate = client:query(sql)
while errmsg == "again" do
result, errmsg, errno, sqlstate = client:read_result()
end
self:close()
if not result then
errmsg = "mysql.query_failed:" .. (errno or "nil") .. (errmsg or "nil")
return false, errmsg, sqlstate
end
return true, result, sqlstate
end
其他
local mysql = require("mysql") -- 调用mysql库
local mysql_pool = {} --初始化连接池
return mysql_pool --设置返回