连接池还是连接迟?
学习玩可以,在生产环境测试效果不理想。
缺点:
1. 不支持复制集
2. 高并发情况下容易 timeout
- mongol_pool.lua
local conf = require "mongol_conf"
local mongol = require("resty.mongol")
local _M = {
_VERSION = "0.1.0"
}
function _M:new(database)
_M.database = database or conf.database
return setmetatable({}, {__index = _M})
end
function _M:get_connect(host, port, timeout)
local host = host or conf.host
local port = port or conf.port
local timeout = timeout or conf.timeout
if ngx.ctx.mongo_client then
return ngx.ctx.mongo_client
end
local conn = mongol:new()
if not conn then
return nil, '### MongoDB initialize failed. ###'
end
conn:set_timeout(timeout)
-- config the ngx.socket.tcp/cosocket built-in connection pool
-- https://github.com/openresty/lua-nginx-module#ngxsockettcp
local pool = conf.username..":"..conf.database..":"..conf.host..":"..conf.port
local pool_size = conf.pool_size
local backlog = conf.backlog
local pool_opts = {
pool = pool,
pool_size = pool_size,
-- backlog = backlog
}
local ok, err = conn:connect(host, port, pool_opts)
if not ok then
return nil, err
end
ngx.ctx.mongo_client = conn
return ngx.ctx.mongo_client,nil
end
function _M:close(keepalive_time, pool_size)
local keepalive_time = keepalive_time or conf.keepalive_time
local pool_size = pool_size or conf.pool_size
if ngx.ctx.mongo_client then
-- no need to manually call the close method on it afterwards.
ngx.ctx.mongo_client:set_keepalive(keepalive_time, pool_size)
ngx.ctx.mongo_client = nil
end
end
function _M:get_col(colname)
local conn, err = _M:get_connect()
if not conn or err then
return nil, '### MongoDB connect failed: '..err..' ###';
end
local database = _M.database or conf.database
local db = conn:new_db_handle(database)
if db == nil then
_M:close()
return nil, '### MongoDB new_db_handle failed. ###'
end
local times,err =conn:get_reused_times()
if 0 == times or nil == times then
local ok, err = db:auth_scram_sha1(conf.username, conf.password)
if ok ~= 1 then
_M:close()
return nil, '### MongoDB auth_scram_sha1 failed: '..err.." ###"
end
else
ngx.log(ngx.ERR, '$$$ reused: ')
ngx.log(ngx.ERR, times)
end
local colname = colname or conf.colname
return db:get_col(colname),nil
end
return _M
- mongol_conf.lua
local _M = {
host = 'your-mongodb-host',
port = 27017,
username = 'standby',
password = 'standby',
database = 'standby',
keepalive_time = 10000,
pool_size = 100,
backlog = 100,
timeout = 10000,
colname = 'test',
}
return _M
作者:Standby — 一生热爱名山大川、草原沙漠,还有我们小郭宝贝!
出处:http://www.cnblogs.com/standby/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/standby/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

浙公网安备 33010602011771号