https://github.com/bigplum/lua-resty-mongol 这个是lua的mongodb驱动,需要安装openresty 1.0.11.7,这里安装1.0.11.28# w
https://github.com/bigplum/lua-resty-mongol 这个是lua的mongodb驱动,需要安装openresty 1.0.11.7,这里安装1.0.11.28
# wget https://openresty.org/download/ngx_openresty-1.0.11.28.tar.gz
# tar xzvf ngx_openresty-1.0.11.28.tar.gz
# cd ngx_openresty-1.0.11.28
# ./configure --prefix=/data/app/openresty --with-luajit && gmake && gmake install
......
# curl https://codeload.github.com/bigplum/lua-resty-mongol/zip/master -o lua-resty-mongol-master.zip
# unzip lua-resty-mongol-master.zip
# make install
# cp -a /usr/local/openresty/lualib/resty/mongol /data/app/openresty/lualib/resty/
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)endlocal 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()endngx.header.content_type="text/explain"if args == nil then ngx.say("error:no args")endlocal 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)endlocal 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: dogage: 12