基於 lua-resty-mongolpython
學習玩能夠,在生產環境測試效果不理想。nginx
缺點:git
1. 不支持複製集github
2. 高併發狀況下容易 timeoutmongodb
- 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.luasocket
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