参考
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;
否则可能会乱码

Java代码  
  1. worker_processes  1;
  2. events {
  3. worker_connections  1024;
  4. }
  5. http {
  6. include       mime.types;
  7. charset utf-8,gbk;
  8. # default_type  application/octet-stream;
  9. default_type text/plain;
  10. lua_package_path "/data/www/lua/?.lua;;";
  11. sendfile        on;
  12. keepalive_timeout  65;
  13. server {
  14. listen       80;
  15. server_name  localhost;
  16. lua_code_cache off;
  17. location /lua {
  18. content_by_lua_file /data/www/lua/test.lua;
  19. }
  20. location /lua_mongo {
  21. content_by_lua_file /data/www/lua/test_mongo.lua;
  22. }
  23. location /lua_get {
  24. content_by_lua_file /data/www/lua/test_get.lua;
  25. }
  26. location / {
  27. root   html;
  28. index  index.html index.htm;
  29. }
  30. #
  31. error_page   500 502 503 504  /50x.html;
  32. location = /50x.html {
  33. root   html;
  34. }
  35. }
  36. }
Java代码  
  1. local redis = require "resty.redis"
  2. local cache = redis.new()
  3. local ok, err = cache.connect(cache, '127.0.0.1', '6379')
  4. cache:set_timeout(60000)
  5. if not ok then
  6. ngx.say("failed to connect:", err)
  7. return
  8. end
  9. res, err = cache:set("dog", "an aniaml")
  10. if not ok then
  11. ngx.say("failed to set dog: ", err)
  12. return
  13. end
  14. ngx.say("set result: ", res)
  15. local res, err = cache:get("dog")
  16. if not res then
  17. ngx.say("failed to get dog: ", err)
  18. return
  19. end
  20. if res == ngx.null then
  21. ngx.say("dog not found.")
  22. return
  23. end
  24. ngx.say("dog: ", res)
  25. local ok, err = cache:close()
  26. if not ok then
  27. ngx.say("failed to close:", err)
  28. return
  29. end

结果

Java代码  
  1. [root@VM_192_107_centos lua]# !curl
  2. curl http://localhost/lua
  3. set result: OK
  4. dog: an aniaml
  5. [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

Java代码  
  1. show dbs
  2. use admin
  3. show collections
  4. db.startup_log.count()
  5. db.startup_log.find()
  6. db.startup_log.find().forEach(function(doc){print(tojson(doc));});
  7. u={name:"haoning",age:21}
  8. db.haoning.insert(u)
  9. db.haoning.insert({name:"ningning",age:10})
  10. db.haoning.find({name:"haoning"});
  11. db.haoning.find({age:18,name:"ning"});
  12. db.haoning.find().sort({age:1});
  13. db.haoning.find().sort({age:-1});
  14. db.haoning.find().limit(2);
  15. db.haoning.find().skip(2).limit(2);
  16. db.haoning.find({age:{$gt:9,$lt:20},name:"ning"});
  17. db.haoning.find({age:{$gt:9,$lt:20}});
  18. $gte $lte $ne
  19. db.haoning.find({age:{$in:[10,18]}});
  20. db.haoning.find({$or:[{age:10},{age:21}]});
  21. db.haoning.update({name:'ning'},{$set:{age:100,sex:0}});
  22. db.haoning.update({name:'haohao'},{$inc:{age:10}},false,true);
  23. db.haoning.findOne({name:"ningning"});
  24. id=db.haoning.findOne({name:"ningning"})._id
  25. db.haoning.remove(id);
  26. db.haoning.ensureIndex({name:1})
  27. db.haoning.ensureIndex({name:1},{backgrand:true})
  28. db.haoning.ensureIndex({name:1},{unique:true})
  29. db.haoning.ensureIndex({created_at:-1})
  30. db.haoning.ensureIndex({name:1,created_at:-1})
  31. 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

Java代码  
  1. local mongo = require "resty.mongol"
  2. local conn = mongo:new()
  3. conn:set_timeout(1000)
  4. local ok, err = conn:connect("127.0.0.1",27017)
  5. if not ok then
  6. ngx.say("connect failed: "..err)
  7. end
  8. local db=conn:new_db_handle("test")
  9. local col = db:get_col("test")
  10. local r = col:find_one({name="dog"},{_id=0})
  11. for k,v in pairs(r) do
  12. ngx.say(k..": "..v)
  13. end

mongo的测试

Java代码  
  1. [root@VM_192_107_centos lua]# mongo
  2. MongoDB shell version: 2.6.6
  3. connecting to: test
  4. > use test
  5. switched to db test
  6. > db.test.insert({name:"dog"})
  7. WriteResult({ "nInserted" : 1 })
  8. > ^C
  9. bye
  10. [root@VM_192_107_centos lua]# ^C
  11. [root@VM_192_107_centos lua]# !curl
  12. curl http://localhost/lua
  13. set result: OK
  14. dog: an aniaml
  15. [root@VM_192_107_centos lua]# curl http://localhost/lua_mongo
  16. name: dog
  17. [root@VM_192_107_centos lua]#

另外,nginx向lua传值

Java代码  
  1. local request_method = ngx.var.request_method
  2. local args = nil
  3. local param = nil
  4. local param2 = nil
  5. if "GET" == request_method then
  6. args = ngx.req.get_uri_args()
  7. elseif "POST" == request_method then
  8. ngx.req.read_body()
  9. args = ngx.req.get_post_args()
  10. end
  11. param = args["p"]
  12. ngx.say("request: ", param)

配置文件:

Java代码  
  1. location /lua_get {
  2. content_by_lua_file /data/www/lua/test_get.lua;
  3. }

测试

Java代码  
  1. [root@VM_192_107_centos lua]# !curl
  2. curl http://localhost/lua_mongo
  3. name: dog
  4. [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了哈

Java代码  
  1. local json = require("cjson")
  2. local request_method = ngx.var.request_method
  3. local args = nil
  4. local param = nil
  5. local param2 = nil
  6. --获取参数的值
  7. if "GET" == request_method then
  8. args = ngx.req.get_uri_args()
  9. elseif "POST" == request_method then
  10. ngx.req.read_body()
  11. args = ngx.req.get_post_args()
  12. end
  13. param = args["param"]
  14. param2 = args["param2"]
  15. --升级版(能处理content-type=multipart/form-data的表单):
  16. local function explode ( _str,seperator )
  17. local pos, arr = 0, {}
  18. for st, sp in function() return string.find( _str, seperator, pos, true ) end do
  19. table.insert( arr, string.sub( _str, pos, st-1 ) )
  20. pos = sp + 1
  21. end
  22. table.insert( arr, string.sub( _str, pos ) )
  23. return arr
  24. end
  25. local args = {}
  26. local file_args = {}
  27. local is_have_file_param = false
  28. local function init_form_args()
  29. local receive_headers = ngx.req.get_headers()
  30. local request_method = ngx.var.request_method
  31. if "GET" == request_method then
  32. args = ngx.req.get_uri_args()
  33. ngx.say("request get: ", args)
  34. elseif "POST" == request_method then
  35. ngx.say("request: post ")
  36. ngx.req.read_body()
  37. ngx.say(string.sub(receive_headers["content-type"],1,33))
  38. --if string.sub(receive_headers["content-type"],1,20) == "multipart/form-data;" then--判断是否是multipart/form-data类型的表单
  39. if string.sub(receive_headers["content-type"],1,33) == "application/x-www-form-urlencoded" then--判断是否是multipart/form-data类型的表单
  40. ngx.say("request: post 1")
  41. is_have_file_param = true
  42. content_type = receive_headers["content-type"]
  43. body_data = ngx.req.get_body_data()--body_data可是符合http协议的请求体,不是普通的字符串
  44. ngx.say("body_data:",body_data)
  45. value = json.encode(body_data)
  46. ngx.say(value)
  47. a = json.decode(value)
  48. ngx.say(a['aa'])
  49. --请求体的size大于nginx配置里的client_body_buffer_size,则会导致请求体被缓冲到磁盘临时文件里,client_body_buffer_size默认是8k或者16k
  50. if not body_data then
  51. local datafile = ngx.req.get_body_file()
  52. if not datafile then
  53. error_code = 1
  54. error_msg = "no request body found"
  55. else
  56. local fh, err = io.open(datafile, "r")
  57. if not fh then
  58. error_code = 2
  59. error_msg = "failed to open " .. tostring(datafile) .. "for reading: " .. tostring(err)
  60. else
  61. fh:seek("set")
  62. body_data = fh:read("*a")
  63. fh:close()
  64. if body_data == "" then
  65. error_code = 3
  66. error_msg = "request body is empty"
  67. end
  68. end
  69. end
  70. end
  71. local new_body_data = {}
  72. --确保取到请求体的数据
  73. if not error_code then
  74. local boundary = "--" .. string.sub(receive_headers["content-type"],31)
  75. local body_data_table = explode(tostring(body_data),boundary)
  76. local first_string = table.remove(body_data_table,1)
  77. local last_string = table.remove(body_data_table)
  78. for i,v in ipairs(body_data_table) do
  79. local start_pos,end_pos,capture,capture2 = string.find(v,'Content%-Disposition: form%-data; name="(.+)"; filename="(.*)"')
  80. if not start_pos then--普通参数
  81. local t = explode(v,"\r\n\r\n")
  82. local temp_param_name = string.sub(t[1],41,-2)
  83. local temp_param_value = string.sub(t[2],1,-3)
  84. args[temp_param_name] = temp_param_value
  85. else--文件类型的参数,capture是参数名称,capture2是文件名
  86. file_args[capture] = capture2
  87. table.insert(new_body_data,v)
  88. end
  89. end
  90. table.insert(new_body_data,1,first_string)
  91. table.insert(new_body_data,last_string)
  92. --去掉app_key,app_secret等几个参数,把业务级别的参数传给内部的API
  93. body_data = table.concat(new_body_data,boundary)--body_data可是符合http协议的请求体,不是普通的字符串
  94. end
  95. else
  96. ngx.say("request: post else")
  97. args = ngx.req.get_post_args()
  98. ngx.say("request: args ",args['p'])
  99. end
  100. end
  101. end
  102. init_form_args()

结果

Java代码  
  1. [root@VM_192_107_centos lualib]# !curl
  2. curl -d "{aa:'cc'}" http://localhost/lua_get_post?p=cc
  3. request: post
  4. application/x-www-form-urlencoded
  5. request: post 1
  6. body_data:{aa:'cc'}
  7. "{aa:'cc'}"
  8. nil
  9. [root@VM_192_107_centos lualib]#

结合mongo加cjson的例子

Java代码  
  1. [root@VM_192_107_centos lua]# cat getChannels.lua
  2. local mongo = require "resty.mongol"
  3. local json = require("cjson")
  4. local conn = mongo:new()
  5. conn:set_timeout(1000)
  6. local ok, err = conn:connect("127.0.0.1",27017)
  7. if not ok then
  8. ngx.say("connect failed: "..err)
  9. end
  10. local db=conn:new_db_handle("meedo-service")
  11. local col = db:get_col("channels")
  12. local r = col:find_one({_id=1})
  13. value = json.encode(r)
  14. ngx.say(value)

来源:http://haoningabc.iteye.com/blog/2165119

nginx lua调用redis和mongo相关推荐

  1. Nginx+Lua脚本+Redis 实现自动封禁访问频率过高IP

    前言:由于公司前几天短信接口被一直攻击,并且攻击者不停变换IP,导致阿里云短信平台上的短信被恶意刷取了几千条,然后在Nginx上对短信接口做了一些限制 临时解决方案: 1.查看Nginx日志发现被攻击 ...

  2. Nginx Lua读取redis 进行权限认证操作

    之前的csdn找不回来了,决定重新注册一个.望支持~~~ 场景:nginx读取redis存储的标识进行重定向或ip拦截 废话不多说,直接lou代码: location /{set $tomcat_ip ...

  3. Nginx+lua 实现调用.so文件方法

    本文给大家分享的是Nginx结合lua 实现调用.so动态链接库文件的方法和示例,有需要的小伙伴可以参考下 最近在和智能硬件部门一起,做一个室内定位的服务,该服务根据手机端传过来的beacon设备列表 ...

  4. nginx lua redis 访问频率限制(转)

    1. 需求分析 Nginx来处理访问控制的方法有多种,实现的效果也有多种,访问IP段,访问内容限制,访问频率限制等. 用Nginx+Lua+Redis来做访问限制主要是考虑到高并发环境下快速访问控制的 ...

  5. nginx+lua+redis 灰度发布实现方案

    背景: 公司要把现有的某传统项目进行微服务化,拆分后要分批次预发布,实现某部分使用户使用微服务模块,其他用户使用传统项目.待微服务稳定.无bug后全部用户迁移至微服务系统. 以上为背景,实现此方案使用 ...

  6. Nginx+Lua+Redis 对请求进行限制

    Nginx+Lua+Redis 对请求进行限制 一.概述 需求:所有访问/myapi/**的请求必须是POST请求,而且根据请求参数过滤不符合规则的非法请求(黑名单), 这些请求一律不转发到后端服务器 ...

  7. nginx+lua+redis deny ip

    2019独角兽企业重金招聘Python工程师标准>>> nginx+lua+redis实现ip黑名单 1.安装LuaJIT LuaJIT LuaJIT即采用C语言写的Lua代码的解释 ...

  8. 利用nginx+lua+redis实现反向代理方法教程

    这篇文章主要给大家介绍了利用nginx+lua+redis实现反向代理方法教程,文中介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面来一起看看吧. 前言 最近因为工作需要,要进行IVR的 ...

  9. windows下nginx+lua+redis实现短域名服务

    nginx+lua+redis 环境搭建: 我使用的是大牛 ZhangYichun 提供的集成包快速安装. 非常简单,下载 ngx_openresty,该集成包中有:Nginx,Lua或Luajit, ...

最新文章

  1. C++字符串数组排序技巧
  2. 从今天开始,学习Webpack,减少对脚手架的依赖(下)
  3. C++、C#写的WebService相互调用
  4. python查看dataframe数据类型_python pandas中DataFrame类型数据操作函数的方法
  5. 网络编程--Address already in use 问题
  6. oracle9i 随机端口_修改 Oracle9i 8080端口问题
  7. spring-beans下的BeanUtils.copyProperties
  8. 两个“敢”,是销售员必须懂的心法
  9. maven java web项目_Maven创建JavaWeb项目
  10. linux resin 自动启动不了,linux下开机启动nginx+resin
  11. 详解: Spark 相对于MapReduce的优势(为什么MapReduce性能不理想)
  12. [转载] 使用selenium_一日一技:使用Selenium的浏览器自动化
  13. Together与Visual.Studio.NET的结合使用(一)
  14. java httpclient 下载_java HttpClient 下载一张图片
  15. 虚拟机出现entering emergency mode,使用xfs_rapair出现Device or resource busy解决
  16. vim编辑器 解决vim编辑异常
  17. 用魔法打败魔法,传染性疫苗能消灭传染病吗?
  18. 计划任务和周期任务mail,at,batch,atq, atrm, cron, crontab
  19. scrapy爬虫之凤凰网热点新闻
  20. lol哪个服务器能玩无限火力,《lol》2021无限火力时间表公告 无限火力什么时候开放...

热门文章

  1. c语言将结果原模原样输出到文件,2013年9月全国计算机二级C语言程序设计上机模考试卷1.docx...
  2. 分布式文档系统-document id的手动指定与自动生成两种方式解析(来自学习笔记:龙果学院ES课程)
  3. 10Linux服务器编程之:opendir()函数,readdir()函数,rewinddir()函数,telldir()函数和seekdir()函数,closedir()函数
  4. 一维数组,二维数组,三维数组,数组与指针,结构体数组,通过改变指针类型改变访问数组的方式
  5. SQL 分组使用案例
  6. ResNet 残差、退化等细节解读
  7. 错误sudo: pip: command not found解决方案
  8. Rainbond v5.1.2发布,微服务架构应用便捷管理和交付
  9. window系统下如何查看so库的信息
  10. hashCode()方法(覆盖hashCode()方法)