侧边栏壁纸
博主头像
落叶人生博主等级

走进秋风,寻找秋天的落叶

  • 累计撰写 130562 篇文章
  • 累计创建 28 个标签
  • 累计收到 9 条评论
标签搜索

目 录CONTENT

文章目录

nginx使用lua直接调用mongodb

2023-12-17 星期日 / 0 评论 / 0 点赞 / 119 阅读 / 2795 字

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

广告 广告

评论区