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

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

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

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

3.使用lua-resty-moongoo模块中的方法操做mongodb,数据库运行过程当中发现少了cbson模块,因此须要先安装cbson模块,github

--
-- 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,安装libbsonmongodb

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服务,访问接口获得结果以下:json

配置文件app

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作简单的操做了curl

相关文章
相关标签/搜索