nginx lua调用redis和mongo

来源:互联网 发布:nseer erp 源码下载 编辑:程序博客网 时间:2024/06/05 22:37
参考 
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.   
  11.     lua_package_path "/data/www/lua/?.lua;;";  
  12.   
  13.     sendfile        on;  
  14.     keepalive_timeout  65;  
  15.   
  16.   
  17.     server {  
  18.         listen       80;  
  19.         server_name  localhost;  
  20.   
  21.         lua_code_cache off;    
  22.   
  23.         location /lua {    
  24.           content_by_lua_file /data/www/lua/test.lua;    
  25.         }    
  26.         location /lua_mongo {    
  27.           content_by_lua_file /data/www/lua/test_mongo.lua;    
  28.         }    
  29.         location /lua_get {     
  30.           content_by_lua_file /data/www/lua/test_get.lua;    
  31.         }   
  32.   
  33.         location / {  
  34.             root   html;  
  35.             index  index.html index.htm;  
  36.         }  
  37.   
  38.   
  39.         #  
  40.         error_page   500 502 503 504  /50x.html;  
  41.         location = /50x.html {  
  42.             root   html;  
  43.         }  
  44.   
  45.     }  
  46.   
  47. }  


Java代码  收藏代码
  1. local redis = require "resty.redis"    
  2.     
  3. local cache = redis.new()    
  4.     
  5. local ok, err = cache.connect(cache, '127.0.0.1''6379')    
  6.     
  7. cache:set_timeout(60000)    
  8.     
  9. if not ok then    
  10.         ngx.say("failed to connect:", err)    
  11.         return    
  12. end    
  13.     
  14. res, err = cache:set("dog""an aniaml")    
  15. if not ok then    
  16.         ngx.say("failed to set dog: ", err)    
  17.         return    
  18. end    
  19.     
  20. ngx.say("set result: ", res)    
  21.     
  22. local res, err = cache:get("dog")    
  23. if not res then    
  24.         ngx.say("failed to get dog: ", err)    
  25.         return    
  26. end    
  27.     
  28. if res == ngx.null then    
  29.         ngx.say("dog not found.")    
  30.         return    
  31. end    
  32.     
  33. ngx.say("dog: ", res)    
  34.     
  35.     
  36. local ok, err = cache:close()    
  37.     
  38. if not ok then    
  39.         ngx.say("failed to close:", err)    
  40.         return    
  41. 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.   
  3. use admin  
  4.   
  5. show collections  
  6.   
  7. db.startup_log.count()  
  8. db.startup_log.find()  
  9. db.startup_log.find().forEach(function(doc){print(tojson(doc));});  
  10.   
  11. u={name:"haoning",age:21}  
  12. db.haoning.insert(u)  
  13. db.haoning.insert({name:"ningning",age:10})  
  14.   
  15.   
  16. db.haoning.find({name:"haoning"});  
  17. db.haoning.find({age:18,name:"ning"});  
  18.   
  19. db.haoning.find().sort({age:1});  
  20. db.haoning.find().sort({age:-1});  
  21.   
  22. db.haoning.find().limit(2);  
  23.   
  24. db.haoning.find().skip(2).limit(2);  
  25.   
  26. db.haoning.find({age:{$gt:9,$lt:20},name:"ning"});  
  27. db.haoning.find({age:{$gt:9,$lt:20}});  
  28. $gte $lte $ne  
  29. db.haoning.find({age:{$in:[10,18]}});  
  30. db.haoning.find({$or:[{age:10},{age:21}]});  
  31.   
  32. db.haoning.update({name:'ning'},{$set:{age:100,sex:0}});  
  33.   
  34.   
  35. db.haoning.update({name:'haohao'},{$inc:{age:10}},false,true);  
  36. db.haoning.findOne({name:"ningning"});  
  37. id=db.haoning.findOne({name:"ningning"})._id  
  38. db.haoning.remove(id);  
  39.   
  40.   
  41. db.haoning.ensureIndex({name:1})  
  42. db.haoning.ensureIndex({name:1},{backgrand:true})  
  43. db.haoning.ensureIndex({name:1},{unique:true})  
  44. db.haoning.ensureIndex({created_at:-1})  
  45. db.haoning.ensureIndex({name:1,created_at:-1})  
  46.   
  47. 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) 
0 0
原创粉丝点击