local mysql = require("resty.mysql")
local exception = require("core.exception")
local dbConf = require("config.mysql")
local sysConf = require("config.system")
local MySQL = {}
--- 获取连接
--
-- @return resty.mysql MySQL连接
-- @error mysql.socketFailed socket建立失败
-- @error mysql.cantConnect 无法连接数据库
-- @error mysql.queryFailed 数据查询失败
function MySQL:getClient()
if ngx.ctx[MySQL] then
return ngx.ctx[MySQL]
end
local client, errmsg = mysql:new()
if not client then
exception:raise("mysql.socketFailed", { message = errmsg })
end
client:set_timeout(3000)
local options = {
user = dbConf.USER,
password = dbConf.PASSWORD,
database = dbConf.DATABASE
}
if dbConf.SOCK then
options.path = dbConf.SOCK
else
options.host = dbConf.HOST
options.port = dbConf.PORT
end
local result, errmsg, errno, sqlstate = client:connect(options)
if not result then
exception:raise("mysql.cantConnect", {
message = errmsg,
code = errno,
state = sqlstate
})
end
local query = "SET NAMES " .. sysConf.DEFAULT_CHARSET
local result, errmsg, errno, sqlstate = client:query(query)
if not result then
exception:raise("mysql.queryFailed", {
query = query,
message = errmsg,
code = errno,
state = sqlstate
})
end
ngx.ctx[MySQL] = client
return ngx.ctx[MySQL]
end