参考 

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

1. worker_processes  1;  
2. events {  
3. 1024;  
4. }  
5. http {  
6.     include       mime.types;  
7. 8,gbk;                                                                                                                                                        
8.    # default_type  application/octet-stream;  
9.      default_type text/plain;  
10.   
11. "/data/www/lua/?.lua;;";  
12.   
13.     sendfile        on;  
14. 65;  
15.   
16.   
17.     server {  
18. 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. 500 502 503 504  /50x.html;  
41.         location = /50x.html {  
42.             root   html;  
43.         }  
44.   
45.     }  
46.   
47. }

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. "failed to connect:", err)    
11. return    
12. end    
13.     
14. res, err = cache:set("dog", "an aniaml")    
15. if not ok then    
16. "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. "failed to get dog: ", err)    
25. return    
26. end    
27.     
28. if res == ngx.null then    
29. "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. "failed to close:", err)    
40. return    
41. end


结果 

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 


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 


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. "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. ": "..v)  
13. end



mongo的测试 


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传值 



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)


配置文件: 


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



测试 


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了哈 

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. 0, {}  
18. for st, sp in function() return string.find( _str, seperator, pos, true ) end do  
19. 1 ) )  
20. 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. "request get: ", args)  
34. "POST" == request_method then  
35. "request: post ")  
36.                 ngx.req.read_body()  
37. "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. "request: post 1")  
41. true  
42. "content-type"]  
43.                         body_data = ngx.req.get_body_data()--body_data可是符合http协议的请求体,不是普通的字符串  
44. "body_data:",body_data)  
45.                         value = json.encode(body_data)  
46.                         ngx.say(value)  
47.                         a = json.decode(value)  
48. '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. 1  
54. "no request body found"  
55. else  
56. "r")  
57. if not fh then  
58. 2  
59. "failed to open " .. tostring(datafile) .. "for reading: " .. tostring(err)  
60. else  
61. "set")  
62. "*a")  
63.                                                 fh:close()  
64. if body_data == "" then  
65. 3  
66. "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. "--" .. string.sub(receive_headers["content-type"],31)  
75.                                 local body_data_table = explode(tostring(body_data),boundary)  
76. 1)  
77.                                 local last_string = table.remove(body_data_table)  
78. for i,v in ipairs(body_data_table) do  
79. 'Content%-Disposition: form%-data; name="(.+)"; filename="(.*)"')  
80. if not start_pos then--普通参数  
81. "\r\n\r\n")  
82. 1],41,-2)  
83. 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. 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. "request: post else")  
97.                         args = ngx.req.get_post_args()  
98. "request: args ",args['p'])  
99.                 end  
100.         end  
101. end  
102. init_form_args()



结果 

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的例子 



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. "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)