https://github.com/bigplum/lua-resty-mongol 這個是lua的mongodb驅動,須要安裝openresty 1.0.11.7,這裏安裝1.0.11.28nginx
# wget https://openresty.org/download/ngx_openresty-1.0.11.28.tar.gzgit
# tar xzvf ngx_openresty-1.0.11.28.tar.gzgithub
# cd ngx_openresty-1.0.11.28mongodb
# ./configure --prefix=/data/app/openresty --with-luajit && gmake && gmake installapp
......curl
# curl https://codeload.github.com/bigplum/lua-resty-mongol/zip/master -o lua-resty-mongol-master.zippost
# unzip lua-resty-mongol-master.zip測試
# make installui
# cp -a /usr/local/openresty/lualib/resty/mongol /data/app/openresty/lualib/resty/lua
tengine配置:
nginx.conf
在http片斷中添加以下行
lua_package_path '/data/app/openresty/lualib/?/init.lua;/data/app/openresty/lualib/?.lua;;';
添加操做mongo的lua腳本
# cat /data/app/tengine/lua/getmongo.lua
local mongo = require "resty.mongol" local conn = mongo:new() conn:set_timeout(1000) local ok, err = conn:connect("127.0.0.1",27017) ngx.header.content_type="text/explain" if not ok then ngx.say("connect failed: "..err) end local db=conn:new_db_handle("test") local col = db:get_col("test") local r = col:find_one({name="dog"},{_id=0}) for k,v in pairs(r) do ngx.say(k..": "..v) end
# cat insertmongo.lua
local request_method = ngx.var.request_method local args = nil if "GET" == request_method then args = ngx.req.get_uri_args() elseif "POST" == request_method then ngx.req.read_body() args = ngx.req.get_post_args() end ngx.header.content_type="text/explain" if args == nil then ngx.say("error:no args") end local mongo = require "resty.mongol" local conn = mongo:new() conn:set_timeout(1000) local ok, err = conn:connect("127.0.0.1",27017) if not ok then ngx.say("connect failed: "..err) end local db = conn:new_db_handle("test") local col = db:get_col("test") local docs = {args} local ist, isterr = col:insert(docs,0,0) if isterr then ngx.say("insert error: "..isterr) else ngx.say("insert success.") end
在tengine的server片斷中添加以下
server
{
listen 80; #listen end server_name 127.0.0.1; #server_name end client_max_body_size 50m; location /mongodb/get { content_by_lua_file /data/app/tengine/lua/getmongo.lua; }
}
往test庫的test表裏插入數據並測試結果
# curl "http://127.0.0.1/mongodb/get" name: dog age: 12