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

相關文章
相關標籤/搜索