OpenResty学习——第二章 OpenResty(Nginx+Lua)开发入门のNginx Lua API

本文转自https://blog.csdn.net/jinnianshilongnian/article/details/84702680,好文要顶,感谢博主分享!

 

Nginx入门

本文目的是学习Nginx+Lua开发,对于Nginx基本知识可以参考如下文章:

nginx启动、关闭、重启

http://www.cnblogs.com/derekchen/archive/2011/02/17/1957209.html

agentzh 的 Nginx 教程

http://openresty.org/download/agentzh-nginx-tutorials-zhcn.html

Nginx+Lua入门

http://17173ops.com/2013/11/01/17173-ngx-lua-manual.shtml

nginx 配置指令的执行顺序

http://zhongfox.github.io/blog/server/2013/05/15/nginx-exec-order/

nginx与lua的执行顺序和步骤说明

http://www.mrhaoting.com/?p=157

Nginx配置文件nginx.conf中文详解

http://www.ha97.com/5194.html

Tengine的Nginx开发从入门到精通

http://tengine.taobao.org/book/

官方文档

http://wiki.nginx.org/Configuration

 

Lua入门

本文目的是学习Nginx+Lua开发,对于Lua基本知识可以参考如下文章:

Lua简明教程

http://coolshell.cn/articles/10739.html

lua在线lua学习教程

http://book.luaer.cn/

Lua 5.1 参考手册

http://www.codingnow.com/2000/download/lua_manual.html

Lua5.3 参考手册

http://cloudwu.github.io/lua53doc/

Nginx Lua API

和一般的Web Server类似,我们需要接收请求、处理并输出响应。而对于请求我们需要获取如请求参数、请求头、Body体等信息;而对于处理就是调用相应的Lua代码即可;输出响应需要进行响应状态码、响应头和响应内容体的输出。因此我们从如上几个点出发即可。

 

接收请求

1、example.conf配置文件 

    location ~ /lua_request/(\d+)/(\d+) {
        #设置nginx变量
        set $a $1; 
        set $b $host;
        default_type "text/html";
        #nginx内容处理
        content_by_lua_file /usr/example/lua/test_request.lua;
        #内容体处理完成后调用
        echo_after_body "ngx.var.b $b";
    }

2、test_request.lua 

--nginx变量
local var = ngx.var
ngx.say("ngx.var.a : ", var.a, "<br/>")
ngx.say("ngx.var.b : ", var.b, "<br/>")
ngx.say("ngx.var[2] : ", var[2], "<br/>")
ngx.var.b = 2;
 
ngx.say("<br/>")
 
--请求头
local headers = ngx.req.get_headers()
ngx.say("headers begin", "<br/>")
ngx.say("Host : ", headers["Host"], "<br/>")
ngx.say("user-agent : ", headers["user-agent"], "<br/>")
ngx.say("user-agent : ", headers.user_agent, "<br/>")
for k,v in pairs(headers) do
    if type(v) == "table" then
        ngx.say(k, " : ", table.concat(v, ","), "<br/>")
    else
        ngx.say(k, " : ", v, "<br/>")
    end
end
ngx.say("headers end", "<br/>")
ngx.say("<br/>")
 
--get请求uri参数
ngx.say("uri args begin", "<br/>")
local uri_args = ngx.req.get_uri_args()
for k, v in pairs(uri_args) do
    if type(v) == "table" then
        ngx.say(k, " : ", table.concat(v, ", "), "<br/>")
    else
        ngx.say(k, ": ", v, "<br/>")
    end
end
ngx.say("uri args end", "<br/>")
ngx.say("<br/>")
 
--post请求参数
ngx.req.read_body()
ngx.say("post args begin", "<br/>")
local post_args = ngx.req.get_post_args()
for k, v in pairs(post_args) do
    if type(v) == "table" then
        ngx.say(k, " : ", table.concat(v, ", "), "<br/>")
    else
        ngx.say(k, ": ", v, "<br/>")
    end
end
ngx.say("post args end", "<br/>")
ngx.say("<br/>")
 
--请求的http协议版本
ngx.say("ngx.req.http_version : ", ngx.req.http_version(), "<br/>")
--请求方法
ngx.say("ngx.req.get_method : ", ngx.req.get_method(), "<br/>")
--原始的请求头内容
ngx.say("ngx.req.raw_header : ",  ngx.req.raw_header(), "<br/>")
--请求的body内容体
ngx.say("ngx.req.get_body_data() : ", ngx.req.get_body_data(), "<br/>")
ngx.say("<br/>")

ngx.var : nginx变量,如果要赋值如ngx.var.b = 2,此变量必须提前声明;另外对于nginx location中使用正则捕获的捕获组可以使用ngx.var[捕获组数字]获取;

ngx.req.get_headers:获取请求头,默认只获取前100,如果想要获取所以可以调用ngx.req.get_headers(0);获取带中划线的请求头时请使用如headers.user_agent这种方式;如果一个请求头有多个值,则返回的是table;

ngx.req.get_uri_args:获取url请求参数,其用法和get_headers类似;

ngx.req.get_post_args:获取post请求内容体,其用法和get_headers类似,但是必须提前调用ngx.req.read_body()来读取body体(也可以选择在nginx配置文件使用lua_need_request_body on;开启读取body体,但是官方不推荐);

ngx.req.raw_header:未解析的请求头字符串;

ngx.req.get_body_data:为解析的请求body体内容字符串。

 

如上方法处理一般的请求基本够用了。另外在读取post内容体时根据实际情况设置client_body_buffer_sizeclient_max_body_size来保证内容在内存而不是在文件中。

 

使用如下脚本测试

wget --post-data 'a=1&b=2' 'http://127.0.0.1/lua_request/1/2?a=3&b=4' -O - 

 

输出响应 

1.1、example.conf配置文件

    location /lua_response_1 {
        default_type "text/html";
        content_by_lua_file /usr/example/lua/test_response_1.lua;
    }

1.2、test_response_1.lua 

--写响应头
ngx.header.a = "1"
--多个响应头可以使用table
ngx.header.b = {"2", "3"}
--输出响应
ngx.say("a", "b", "<br/>")
ngx.print("c", "d", "<br/>")
--200状态码退出
return ngx.exit(200)

ngx.header:输出响应头;

ngx.print:输出响应内容体;

ngx.say:通ngx.print,但是会最后输出一个换行符;

ngx.exit:指定状态码退出。

 

2.1、example.conf配置文件

    location /lua_response_2 {
        default_type "text/html";
        content_by_lua_file /usr/example/lua/test_response_2.lua;
    }

 

2.2、test_response_2.lua

ngx.redirect("http://jd.com", 302)

ngx.redirect:重定向; 

 

ngx.status=状态码,设置响应的状态码;ngx.resp.get_headers()获取设置的响应状态码;ngx.send_headers()发送响应状态码,当调用ngx.say/ngx.print时自动发送响应状态码;可以通过ngx.headers_sent=true判断是否发送了响应状态码。

 

其他API

1、example.conf配置文件

    location /lua_other {
        default_type "text/html";
        content_by_lua_file /usr/example/lua/test_other.lua;
    }

 

2、test_other.lua

--未经解码的请求uri
local request_uri = ngx.var.request_uri;
ngx.say("request_uri : ", request_uri, "<br/>");
--解码
ngx.say("decode request_uri : ", ngx.unescape_uri(request_uri), "<br/>");
--MD5
ngx.say("ngx.md5 : ", ngx.md5("123"), "<br/>")
--http time
ngx.say("ngx.http_time : ", ngx.http_time(ngx.time()), "<br/>")

 

ngx.escape_uri/ngx.unescape_uri : uri编码解码;

ngx.encode_args/ngx.decode_args:参数编码解码;

ngx.encode_base64/ngx.decode_base64:BASE64编码解码;

ngx.re.match:nginx正则表达式匹配;

 

更多Nginx Lua API请参考 http://wiki.nginx.org/HttpLuaModule#Nginx_API_for_Lua

 

Nginx全局内存

使用过如Java的朋友可能知道如Ehcache等这种进程内本地缓存,Nginx是一个Master进程多个Worker进程的工作方式,因此我们可能需要在多个Worker进程中共享数据,那么此时就可以使用ngx.shared.DICT来实现全局内存共享。

 

1、首先在nginx.conf的http部分分配内存大小

    #共享全局变量,在所有worker间共享
    lua_shared_dict shared_data 1m;

 

2、example.conf配置文件

    location /lua_shared_dict {
        default_type "text/html";
        content_by_lua_file /usr/example/lua/test_lua_shared_dict.lua;
    }

3、 test_lua_shared_dict.lua

--1、获取全局共享内存变量
local shared_data = ngx.shared.shared_data
 
--2、获取字典值
local i = shared_data:get("i")
if not i then
    i = 1
    --3、惰性赋值
    shared_data:set("i", i)
    ngx.say("lazy set i ", i, "<br/>")
end
--递增
i = shared_data:incr("i", 1)
ngx.say("i=", i, "<br/>")

更多API请参考http://wiki.nginx.org/HttpLuaModule#ngx.shared.DICT。 

 

 

到此基本的Nginx Lua API就学完了,对于请求处理和输出响应如上介绍的API完全够用了,更多API请参考官方文档。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值