openresty 配置 mongodb 可操作插件


1、下載lua-resty-mongol https://github.com/bigplum/lua-resty-mongol

2、配置_mongo.conf文件,在conf創建_mongo.conf文件,配置信息如下

#_mongo.conf  
server {
        listen   89;
        #server_name 192.168.1.128;
        #關閉lua_code 緩存

        location /lua {
                content_by_lua_file  /opt/openresty/lualib/resty/mongol/test_lua.lua;
        }
        location /lua_mongo {
                content_by_lua_file lualib/resty/mongol/test_mongol.lua;
 
        }
        location /lua_test {
                set $test "hello world";
                #使用acess 階段做准入條件處理
                access_by_lua '
                        if (ngx.var.test =="hello world") then 
                                ngx.say("驗證通過"..ngx.var.test)
                        else 
                                ngx.log(ngx.ERR,"驗證失敗","")
                        end
                ';
                #業務處理
                content_by_lua '
                        ngx.header.content_type ="text/plain";
                        local a, b =1;
                        ngx.say(ngx.var.test..a);
                ';
        }


}

然后記得把_mongo.conf配到主配置文件上,在nginx.conf里添加【include _mongo.conf; 】

3、在content_by_lua_file lualib/resty/mongol/文件夾下創建數據庫的測試文件test_mongol.lua,代碼如下:

local mongo =require "resty.mongol"
local json = require "cjson"
--獲取連接對象
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("testdb")
--用戶授權
local ok ,err = db:auth("","")

if ok then 
        ngx.say("user auth success"..ok)
end 
--獲取集合
local coll = db:get_col("testtable")
--獲取document集合
local cursor = coll:find({})

--json 轉碼
--
function json_decode( str )
        local json_value =nil
        pcall(function (str) json_value = json.decode(str) end, str)
        return json_value 
end

--循環 
for index,item in cursor:pairs() do
        ngx.say('數據: '..index)
        if not item['url'] then 
                ngx.say('數據:'..item["title"])
        else
                ngx.say('數據:'..item["title"]..item['url'])
                ngx.say(json_decode(item['url']))
        end

end
--獲取單個集合
local res =coll:find_one({key = 150})

if res then 

        ngx.say(res['title'])
end

--插入集合
local bson1 ={title ='哈哈',url = 'www.baidu.com',key = 300};
--插入table 表中 
local docs ={bson1};

local rsOk,err =coll:insert(docs,0,0)

if err then 
        ngx.say('error--'..err)
else 
        ngx.say('ok---- '..rsOk)
end

--刪除操作
local deOk,err = coll:delete({title ='你好'},0,0)

if err then 
        ngx.say('delete error--'..err)
else
        ngx.say('delete ok--'..deOk)
end

--關閉連接
if conn then 

        conn:close()
end 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM