nginx使用lua直接调用mongodb

本文介绍了如何安装Lua的MongoDB驱动lua-resty-mongol,并通过示例展示了如何使用此驱动连接MongoDB数据库,执行读写操作。此外,还提供了在OpenResty环境下部署Lua脚本的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)
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

转载于:https://my.oschina.net/u/1791060/blog/760015

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值