`
haoningabc
  • 浏览: 1469935 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

nginx lua调用redis和mongo

阅读更多
参考
http://blog.csdn.net/vboy1010/article/details/7892120
http://www.zhangjixuem.com.cn/2014/4/1/01037.html

https://github.com/bigplum/lua-resty-mongol
安装:
下载ngx_openresty-1.7.2.1.tar.gz
./configure --prefix=/data/nginx/openresty/resty --with-luajit
make
make install
修改nginx.conf
注意default_type text/plain;
否则浏览器触发是下载
charset utf-8,gbk;
否则可能会乱码
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    charset utf-8,gbk;                                                                                                                                                      
   # default_type  application/octet-stream;
     default_type text/plain;

    lua_package_path "/data/www/lua/?.lua;;";

    sendfile        on;
    keepalive_timeout  65;


    server {
        listen       80;
        server_name  localhost;

        lua_code_cache off;  

        location /lua {  
          content_by_lua_file /data/www/lua/test.lua;  
        }  
        location /lua_mongo {  
          content_by_lua_file /data/www/lua/test_mongo.lua;  
        }  
        location /lua_get {   
          content_by_lua_file /data/www/lua/test_get.lua;  
        } 

        location / {
            root   html;
            index  index.html index.htm;
        }


        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }

}


local redis = require "resty.redis"  
  
local cache = redis.new()  
  
local ok, err = cache.connect(cache, '127.0.0.1', '6379')  
  
cache:set_timeout(60000)  
  
if not ok then  
        ngx.say("failed to connect:", err)  
        return  
end  
  
res, err = cache:set("dog", "an aniaml")  
if not ok then  
        ngx.say("failed to set dog: ", err)  
        return  
end  
  
ngx.say("set result: ", res)  
  
local res, err = cache:get("dog")  
if not res then  
        ngx.say("failed to get dog: ", err)  
        return  
end  
  
if res == ngx.null then  
        ngx.say("dog not found.")  
        return  
end  
  
ngx.say("dog: ", res)  
  
  
local ok, err = cache:close()  
  
if not ok then  
        ngx.say("failed to close:", err)  
        return  
end 


结果
[root@VM_192_107_centos lua]# !curl
curl http://localhost/lua
set result: OK
dog: an aniaml
[root@VM_192_107_centos lua]#

#---------------mongo的基本操作--------------
http://wenku.baidu.com/link?url=K2rmB_5ypVHErZPvi1UucFXfnfEXk4IrvgSQzeSabKJx50W_gpD2cFvCEPQZm0sZgMvHGJTmZahK96Ee3n7OgZTb4gHgybQdZsQ2xGV4nZm

启动mongo
./mongod --dbpath=../data/db --logpath=../log/mongodb.log
show dbs

use admin

show collections

db.startup_log.count()
db.startup_log.find()
db.startup_log.find().forEach(function(doc){print(tojson(doc));});

u={name:"haoning",age:21}
db.haoning.insert(u)
db.haoning.insert({name:"ningning",age:10})


db.haoning.find({name:"haoning"});
db.haoning.find({age:18,name:"ning"});

db.haoning.find().sort({age:1});
db.haoning.find().sort({age:-1});

db.haoning.find().limit(2);

db.haoning.find().skip(2).limit(2);

db.haoning.find({age:{$gt:9,$lt:20},name:"ning"});
db.haoning.find({age:{$gt:9,$lt:20}});
$gte $lte $ne
db.haoning.find({age:{$in:[10,18]}});
db.haoning.find({$or:[{age:10},{age:21}]});

db.haoning.update({name:'ning'},{$set:{age:100,sex:0}});


db.haoning.update({name:'haohao'},{$inc:{age:10}},false,true);
db.haoning.findOne({name:"ningning"});
id=db.haoning.findOne({name:"ningning"})._id
db.haoning.remove(id);


db.haoning.ensureIndex({name:1})
db.haoning.ensureIndex({name:1},{backgrand:true})
db.haoning.ensureIndex({name:1},{unique:true})
db.haoning.ensureIndex({created_at:-1})
db.haoning.ensureIndex({name:1,created_at:-1})

db.haoning.distinct("name");


mongo的安装

git clone https://github.com/bigplum/lua-resty-mongol.git
make PREFIX=/data/nginx/openresty/resty install
/data/nginx/openresty/resty 为已经安装的resty的安装路径
会在/data/nginx/openresty/resty/lualib/resty
下面添加mongol的一些lua脚本

mongo的test的lua脚本:
参考
http://www.zhangjixuem.com.cn/2014/4/1/01037.html
local mongo = require "resty.mongol"
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("test")
local col = db:get_col("test")
local r = col:find_one({name="dog"},{_id=0})
for k,v in pairs(r) do
   ngx.say(k..": "..v)
end

mongo的测试
[root@VM_192_107_centos lua]# mongo 
MongoDB shell version: 2.6.6
connecting to: test
> use test
switched to db test
> db.test.insert({name:"dog"})
WriteResult({ "nInserted" : 1 })
> ^C
bye
[root@VM_192_107_centos lua]# ^C
[root@VM_192_107_centos lua]# !curl
curl http://localhost/lua
set result: OK
dog: an aniaml
[root@VM_192_107_centos lua]# curl http://localhost/lua_mongo
name: dog
[root@VM_192_107_centos lua]# 




另外,nginx向lua传值
local request_method = ngx.var.request_method
local args = nil
local param = nil
local param2 = nil
if "GET" == request_method then
    args = ngx.req.get_uri_args()
elseif "POST" == request_method then
    ngx.req.read_body()
    args = ngx.req.get_post_args()
end
param = args["p"]
ngx.say("request: ", param)

配置文件:

location /lua_get {   
          content_by_lua_file /data/www/lua/test_get.lua;  
        }  

测试
[root@VM_192_107_centos lua]# !curl
curl http://localhost/lua_mongo
name: dog
[root@VM_192_107_centos lua]#


[root@VM_192_107_centos sbin]# curl -d "p='bbb'" http://127.0.0.1/lua_get?  
post
request: 'bbb'
[root@VM_192_107_centos sbin]#
参考http://www.server110.com/nginx/201310/2800.html

#-----------------使用request的 data_body,及json的参数--------
[root@VM_192_107_centos lualib]# ls
cjson.so  rds  redis  resty
[root@VM_192_107_centos lualib]# pwd
/data/nginx/openresty/resty/lualib
看下面有个cjson.so
就是可以require cjson了哈
local json = require("cjson")
local request_method = ngx.var.request_method
local args = nil
local param = nil
local param2 = nil
--获取参数的值
if "GET" == request_method then
    args = ngx.req.get_uri_args()
elseif "POST" == request_method then
    ngx.req.read_body()
    args = ngx.req.get_post_args()
end
param = args["param"]
param2 = args["param2"]
--升级版(能处理content-type=multipart/form-data的表单):
local function explode ( _str,seperator )
        local pos, arr = 0, {}
                for st, sp in function() return string.find( _str, seperator, pos, true ) end do
                        table.insert( arr, string.sub( _str, pos, st-1 ) )
                        pos = sp + 1
                end
        table.insert( arr, string.sub( _str, pos ) )
        return arr
end
local args = {}
local file_args = {}
local is_have_file_param = false
local function init_form_args()
        local receive_headers = ngx.req.get_headers()
        local request_method = ngx.var.request_method
        if "GET" == request_method then
                args = ngx.req.get_uri_args()
                ngx.say("request get: ", args)
        elseif "POST" == request_method then
                ngx.say("request: post ")
                ngx.req.read_body()
                ngx.say(string.sub(receive_headers["content-type"],1,33))
                --if string.sub(receive_headers["content-type"],1,20) == "multipart/form-data;" then--判断是否是multipart/form-data类型的表单
                if string.sub(receive_headers["content-type"],1,33) == "application/x-www-form-urlencoded" then--判断是否是multipart/form-data类型的表单
                        ngx.say("request: post 1")
                        is_have_file_param = true
                        content_type = receive_headers["content-type"]
                        body_data = ngx.req.get_body_data()--body_data可是符合http协议的请求体,不是普通的字符串
                        ngx.say("body_data:",body_data)
                        value = json.encode(body_data)
                        ngx.say(value)
                        a = json.decode(value)
                        ngx.say(a['aa'])
                        --请求体的size大于nginx配置里的client_body_buffer_size,则会导致请求体被缓冲到磁盘临时文件里,client_body_buffer_size默认是8k或者16k
                        if not body_data then
                                local datafile = ngx.req.get_body_file()
                                if not datafile then
                                        error_code = 1
                                        error_msg = "no request body found"
                                else
                                        local fh, err = io.open(datafile, "r")
                                        if not fh then
                                                error_code = 2
                                                error_msg = "failed to open " .. tostring(datafile) .. "for reading: " .. tostring(err)
                                        else
                                                fh:seek("set")
                                                body_data = fh:read("*a")
                                                fh:close()
                                                if body_data == "" then
                                                        error_code = 3
                                                        error_msg = "request body is empty"
                                                end
                                        end
                                end
                        end
                        local new_body_data = {}
                        --确保取到请求体的数据
                        if not error_code then
                                local boundary = "--" .. string.sub(receive_headers["content-type"],31)
                                local body_data_table = explode(tostring(body_data),boundary)
                                local first_string = table.remove(body_data_table,1)
                                local last_string = table.remove(body_data_table)
                                for i,v in ipairs(body_data_table) do
                                        local start_pos,end_pos,capture,capture2 = string.find(v,'Content%-Disposition: form%-data; name="(.+)"; filename="(.*)"')
                                        if not start_pos then--普通参数
                                                local t = explode(v,"\r\n\r\n")
                                                local temp_param_name = string.sub(t[1],41,-2)
                                                local temp_param_value = string.sub(t[2],1,-3)
                                                args[temp_param_name] = temp_param_value
                                        else--文件类型的参数,capture是参数名称,capture2是文件名
                                                file_args[capture] = capture2
                                                table.insert(new_body_data,v)
                                        end
                                end
                                table.insert(new_body_data,1,first_string)
                                table.insert(new_body_data,last_string)
                                --去掉app_key,app_secret等几个参数,把业务级别的参数传给内部的API
                                body_data = table.concat(new_body_data,boundary)--body_data可是符合http协议的请求体,不是普通的字符串
                        end
                else
                        ngx.say("request: post else")
                        args = ngx.req.get_post_args()
                        ngx.say("request: args ",args['p'])
                end
        end
end
init_form_args()

结果
[root@VM_192_107_centos lualib]# !curl
curl -d "{aa:'cc'}" http://localhost/lua_get_post?p=cc
request: post 
application/x-www-form-urlencoded
request: post 1
body_data:{aa:'cc'}
"{aa:'cc'}"
nil
[root@VM_192_107_centos lualib]#




结合mongo加cjson的例子
[root@VM_192_107_centos lua]# cat getChannels.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("meedo-service")
local col = db:get_col("channels")
local r = col:find_one({_id=1})
value = json.encode(r)
ngx.say(value)
分享到:
评论

相关推荐

    nginx+lua+redis 集群 连接插件和脚本

    在构建高性能、高可用性的Web服务时,常常会利用到Nginx作为反向代理和负载均衡器,Lua作为扩展Nginx功能的脚本语言,而Redis则作为内存数据存储,提供快速的数据访问。本资源包“nginx+lua+redis集群 连接插件和...

    nginx+lua+redis通过匹配客户端ip进行灰度发布

    本文将讲述如何使用nginx、lua和redis来实现灰度发布,通过匹配客户端IP来实现灰度发布。灰度发布是一种常见的软件发布方式,它允许开发者在生产环境中发布新的版本,同时仍然保留旧版本,以便在出现问题时快速回退...

    nginx+lua+redis实现token验证

    `lua`作为轻量级的脚本语言,可以增强`nginx`的功能,而`redis`则常用于高速缓存和分布式数据存储。本文将深入探讨如何利用`nginx+lua+redis`来实现`token`验证,以确保只有经过授权的用户才能访问受保护的资源。 ...

    Nginx+Lua+Redis+Json

    "Nginx、Lua、Redis 和 Json 的结合应用" Nginx 是一个高性能的 Web 服务器, Lua 是一种轻量级的脚本语言,而 Redis 是一个高性能的 NoSQL 数据库, Json 是一种轻量级的数据交换格式。通过结合使用这些技术,可以...

    linux 实现nginx+Lua 访问redis集群

    最近有个需求是需要用nginx播放服务器的视频,考虑安全问题,需要在nginx加个lua去取redis...1、内部含有liunx下安装nginx和lua环境所需的安装包 2、有本人亲自验证过的安装步骤。 3、替换里面jq_uat.lua的redis配置。

    ngx_lua_php_queue, nginx lua php redis实现单业务排队系统架构.zip

    部署此类系统需要对Nginx、lua、PHP和Redis的配置有深入理解。开发者需要根据具体环境调整各项参数,确保系统的稳定性和高效性。 通过以上介绍,我们可以看出ngx_lua_php_queue是一个利用现有技术栈构建的灵活且可...

    Nginx+Lua+Redis构建高并发Web应用

    在构建高性能Web应用程序时,Nginx、Lua和Redis的组合提供了一种高效且灵活的解决方案。这种架构允许处理高并发请求,同时减轻服务器压力,提高响应速度。下面将详细介绍如何利用这三种技术来构建这样的系统。 首先...

    nginx+lua+redis黑名单加载

    综上所述,"nginx+lua+redis黑名单加载"是一种有效的网络安全策略,通过利用`nginx`的高性能和`lua`的灵活性,结合`redis`的快速存取能力,能够实时阻止黑名单中的IP进行访问,保护服务器资源和用户数据的安全。...

    nginx+lua+redis.rar

    在现代Web服务的构建中,Nginx、Lua和Redis已经成为一种高效的组合,它们各自承担着不同的角色,共同构建出高并发、低延迟的系统。Nginx作为前端服务器,负责处理HTTP请求,Lua则用于提供灵活的脚本语言支持,而...

    Nginx利用Lua+Redis实现动态封禁IP的方法

    本文给大家介绍的是Nginx利用Lua+Redis实现动态封禁IP的方法,下面话不多说了,来一起看看详细的介绍吧 二、架构 实现 IP 黑名单的功能有很多途径: 1、在操作系统层面,配置 iptables,拒绝指定 IP 的网络请求; 2...

    lua+redis+nginx

    在构建高性能服务器架构时,`Lua`、`Redis` 和 `Nginx` 的结合使用是一种常见的技术方案。本文将详细探讨这三个组件及其在构建高效系统中的作用。 首先,`Lua` 是一种轻量级的脚本语言,以其简洁的语法、高效的执行...

    2 OpenResty+Lua+Redis 高性能后端接口.docx

    在 Nginx 配置文件中,我们需要添加一个 Location 块来调用 Lua 脚本: ```nginx location /content_update { content_by_lua_file /root/lua/content_update.lua; } ``` 最后,我们需要重新启动 Nginx 并测试我们...

    跟我学Nginx+Lua开发_nginxlua原理_nginx_

    Nginx以其高性能、反向代理和负载均衡能力而闻名,而Lua则是一种轻量级的脚本语言,两者结合可以实现强大的服务器端功能。 一、Nginx基础 Nginx是一款开源的HTTP服务器,采用事件驱动的异步非阻塞模型,具有高并发...

    nginx 整合redis以及lua语言

    在IT行业中,尤其是在Web...总结来说,整合Nginx、Redis和Lua是一种高效的方法,可以充分利用各自的优势,构建高性能、可扩展的Web服务架构。通过使用上述工具和模块,开发者可以创建出更灵活、更强大的Web应用程序。

    lua-redis:lua reis nginx 配制 及 redis.lua 脚本

    lua-redis lua reis nginx 配制 及 redis.lua 脚本 redis.lua 脚本 支持 get, post redis 的hash, 及 集合 命令 开启redis的密码认证...nginxlua.conf 配制 lua地址: 示列: redis_lib.php 为PHP类包 redis_lua 类

    lua版waf web防火墙 redis+nginx版

    **lua版WAF Web防火墙**是针对Web应用程序的安全防护系统,...总之,lua版WAF Web防火墙结合Redis和OpenResty Nginx,提供了一种高效且灵活的Web安全解决方案,能够有效地保护网站免受恶意攻击,同时便于管理和扩展。

    【Redis开发】lua脚本开发nginx 与 redis 模块

    【Redis开发】lua脚本开发nginx 与 redis 模块 (Lua script development nginx and Redis modules) 文件列表: lua_files (0, 2017-05-21) lua_files\access_control.lua (1813, 2017-05-21) lua_files\app_redis_...

    Redis+nginx集群部署

    本文将详述如何使用Tomcat、Nginx和Redis来搭建这样的集群,并着重讲解Session共享的问题,因为这是多服务器环境中的关键挑战。 **标题:Redis+nginx集群部署** **描述:**在本实践中,我们将结合Tomcat应用服务器...

    nginx+redis负载均衡、session共享

    总的来说,"nginx+redis负载均衡、session共享"的架构提高了Web服务的可扩展性和可靠性,确保了用户在多台服务器间的会话一致性。在实际部署时,还需要考虑如容错处理、性能监控、安全策略等更多细节,以构建更健壮...

Global site tag (gtag.js) - Google Analytics