openresty利用插件lua-resty-moongoo操作mongodb

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

1.引入第三方模块lua-resty-moongoo

https://github.com/isage/lua-resty-moongoo.git

2.将其下载下来放到/usr/local/openresty/lualib/resty路径下

openresty利用插件lua-resty-moongoo操作mongodb_第1张图片

3.使用lua-resty-moongoo模块中的方法操作mongodb,数据库运行过程中发现少了cbson模块,所以需要先安装cbson模块,

--
-- Created by IntelliJ IDEA.
-- User: guanguan
-- Date: 2017/11/7
-- Time: 上午9:43
-- To change this template use File | Settings | File Templates.
--
local moongoo = require("resty.moongoo")
local cbson =require("cbson")
local cjson=require("cjson.safe")

local mg, err = moongoo.new("mongodb://127.0.0.1:27017")
if not mg then
    error(err)
end


local col=mg:db("myDbs"):collection("myTable")


local ids,err=col:insert({name="guanguan",age=23})
--ngx.log(ngx.ERR,err)
local doc, err = col:find_one({ name = "guanguan"})

ngx.say("age::",doc.age)

mg:close()








 

4.cbson主要用来生成mongo中的objectId,安装libbson

git clone git://github.com/mongodb/libbson.git
cd libbson/
./autogen.sh  #运行此命令时会报缺少libtoolize的错误 ,此时要安装libtool ,automake,autoconf三个工具可以解决
brew install libtool
brew install automake
brew install autoconf

make
make install

make clean && make LUA_INCLUDE_DIR=/usr/local/openresty/luajit/include/luajit-2.1 LUA_CMODULE_DIR=/usr/local/openresty/lualib LUA_MODULE_DIR=/usr/local/openresty/lualib CBSON_CFLAGS="-g -fpic -I/usr/local/include/libbson-1.0/ " CC=cc


5.安装使用cbson

git clone https://github.com/isage/lua-cbson.git
cd lua-cbson
mkdir build
cd build
cmake ..
make
make install

6.运行nginx服务,访问接口得到结果如下:

配置文件

    server {
        listen       8001;
        server_name  localhost;

        lua_code_cache off;


        set $path /Users/guanguan/workspace/testMongo;

 
        location /test/mongo {
            access_by_lua_file  $path/test.lua;
        }

    access_log   /usr/local/openresty/nginx/logs/mongo_access.log  main;
    error_log    /usr/local/openresty/nginx/logs/mongo_error.log  debug;
    }
➜  ~ curl -i http://localhost:8001/test/mongo
HTTP/1.1 200 OK
Server: openresty/1.9.7.4
Date: Tue, 07 Nov 2017 06:39:44 GMT
Content-Type: application/octet-stream
Transfer-Encoding: chunked
Connection: keep-alive

age::23
➜  ~

说明已经可以对mongodb做简单的操作了

转载于:https://my.oschina.net/u/2263272/blog/1563801

你可能感兴趣的:(openresty利用插件lua-resty-moongoo操作mongodb)