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