Openresty的lua编程--1
目录:
使用openresty生成响应
/usr/servers/nginx/conf/lua/test.lua
ngx.say("hello world");
nginx配置
location /lua {
default_type 'text/html';
content_by_lua_file conf/lua/test.lua; #相对于nginx安装目录
}
默认情况下lua_code_cache
是开启的,即缓存lua代码,即每次lua代码变更必须reload nginx
才生效,如果在开发阶段可以通过lua_code_cache off;
关闭缓存,这样调试时每次修改lua代码不需要reload nginx
但是正式环境一定记得开启缓存
其他配置简介
#user nobody;
worker_processes 2;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type text/html;
#lua模块路径,其中”;;”表示默认搜索路径,默认到/usr/servers/nginx下找
lua_package_path "/usr/example/lualib/?.lua;;"; #lua 模块
lua_package_cpath "/usr/example/lualib/?.so;;"; #c模块
include /usr/example/example.conf;
}
server {
listen 80;
server_name _;
location /lua {
default_type 'text/html';
lua_code_cache off;
content_by_lua_file /usr/example/lua/test.lua;
}
}
Nginx的luaapi
主要就是
- 接受请求,获取请求参数,请求头和Body体
- 处理请求
- 输出响应,包括响应状态码,响应头和响应内容
接受请求
配置在content_by_lua_file
阶段使用test_request.lua文件
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";
}
设置返回的结果
--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体内容字符串。
测试一下
$ wget --post-data 'a=1&b=2' 'http://127.0.0.1/lua_request/1/2?a=3&b=4' -O -
响应结果
ngx.var.a : 1<br/>ngx.var.b : 127.0.0.1<br/>
ngx.var[2] : 2<br/> # 可以看到直接获取的就是正则匹配的结果
<br/>
headers begin<br/>
Host : 127.0.0.1:81<br/>
user-agent : Wget/1.14 (linux-gnu)<br/>
user-agent : Wget/1.14 (linux-gnu)<br/>
host : 127.0.0.1:81<br/>
content-type : application/x-www-form-urlencoded<br/>
connection : Keep-Alive<br/>
accept : */*<br/>
content-length : 7<br/>
user-agent : Wget/1.14 (linux-gnu)<br/>
headers end<br/>
<br/>
uri args begin<br/>
a: 3<br/>
b: 4<br/>
uri args end<br/>
<br/>
post args begin<br/>
b: 2<br/>
a: 1<br/>
post args end<br/>
<br/>
ngx.req.http_version : 1.1<br/>
ngx.req.get_method : POST<br/>
ngx.req.raw_header : POST /lua_request/1/2?a=3&b=4 HTTP/1.1
User-Agent: Wget/1.14 (linux-gnu)
Accept: */*
Host: 127.0.0.1:81
Connection: Keep-Alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 7
<br/>
ngx.req.get_body_data() : a=1&b=2<br/>
<br/>
ngx.var.b 2
输出响应
配置nginx
location /lua_response_1 {
default_type "text/html";
content_by_lua_file /home/openresty/nginx/conf/test_response_1.lua;
}
配置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:指定状态码退出。
测试一下
$ curl -i -XGET 127.0.0.1:81/lua_response_1
响应结果
HTTP/1.1 200 OK
Server: openresty/1.15.8.1
Date: Thu, 15 Aug 2019 10:02:06 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
a: 1
b: 2
b: 3
ab<br/>
cd<br/>
- ngx.redirect:重定向;
- ngx.status状态码,设置响应的状态码;
ngx.resp.get_headers()
获取设置的响应状态码;ngx.send_headers()
发送响应状态码,当调用ngx.say/ngx.print时自动发送响应状态码;可以通过ngx.headers_sent=true
判断是否发送了响应状态码。
测试一下
$ curl -i -XGET 127.0.0.1:81/lua_response_2
响应结果
HTTP/1.1 302 Moved Temporarily
Server: openresty/1.15.8.1
Date: Fri, 16 Aug 2019 03:54:25 GMT
Content-Type: text/html
Content-Length: 151
Connection: keep-alive
Location: http://jd.com
<html>
<head><title>302 Found</title></head>
<body>
<center><h1>302 Found</h1></center>
<hr><center>openresty/1.15.8.1</center>
</body>
</html>
其他
ngx.escape_uri/ngx.unescape_uri
: uri编码解码;ngx.encode_args/ngx.decode_args
:参数编码解码;ngx.encode_base64/ngx.decode_base64
:BASE64编码解码;ngx.re.match
:nginx正则表达式匹配
location /lua_other {
default_type "text/html";
content_by_lua_file /home/openresty/nginx/conf/test_other.lua;
}
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/>")
进行请求
curl -i -XGET 127.0.0.1:81/lua_other
响应结果
HTTP/1.1 200 OK
Server: openresty/1.15.8.1
Date: Fri, 16 Aug 2019 09:26:18 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
request_uri : /lua_other<br/>
decode request_uri : /lua_other<br/>
ngx.md5 : 202cb962ac59075b964b07152d234b70<br/>
ngx.http_time : Fri, 16 Aug 2019 09:26:18 GMT<br/>
Nginx全局内存
#共享全局变量,在所有worker间共享
lua_shared_dict shared_data 1m;
参考官方wiki
nginx配置
location /lua_args {
default_type "text/html";
content_by_lua_file /home/openresty/nginx/conf/test_args.lua;
}
test_args.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/>")
请求和响应
$ curl 127.0.0.1:81/lua_args
lazy set i 1<br/>
i=2<br/>
$ curl 127.0.0.1:81/lua_args
i=3<br/>
$ curl 127.0.0.1:81/lua_args
i=4<br/>
Nginx模块指令
可以在nginx的11个阶段进行插入式处理,可在server,location,if等范围配置
指令 | 处理阶段 | 使用范围 | 解释 |
---|---|---|---|
init_by_lua 和init_by_lua_file |
loading-config | http | 在master加载配置执行,用于初始化全局配置或者预加载lua模块 |
init_worker_by_lua 和init_worker_by_lua_file |
starting-worker | http | Worker进程启动时调用的计时器,如果Master进程不允许则只会在init_by_lua 之后调用,通常用于定时拉取配置/数据,或者后端服务的健康检查 |
set_by_lua 和set_by_lua_file |
rewrite | server,server if,location,location if | 设置nginx变量,可以实现复杂的赋值逻辑,此处是阻塞的,Lua代码要做到非常快 |
rewrite_by_lua 和rewrite_by_lua_file |
rewrite tail | http,server,location,location if | rewrite阶段处理,可以实现复杂的转发/重定向逻辑 |
access_by_lua 和access_by_lua_file |
access tail | http,server,location,location if | 请求访问阶段处理,用于访问控制 |
content_by_lua 和content_by_lua_file |
content | location,location if | 内容处理器,接收请求处理并输出响应 |
header_filter_by_lua 和header_filter_by_lua_file |
output-header-filter | http,server,location,location if | 设置header和cookie |
body_filter_by_lua 和body_filter_by_lua_file |
output-body-filter | http,server,location,location if | 对响应数据进行过滤,比如截断、替换。 |
log_by_lua 和log_by_lua_file |
log | http,server,location,location if | log阶段处理,比如记录访问量/统计平均响应时间 |
更多参考官方文档
init_by_lua
nginx配置
http部分
#共享全局变量,在所有worker间共享
lua_shared_dict shared_data 1m;
init_by_lua_file /home/openresty/nginx/conf/init.lua;
server部分
location /lua_init {
default_type "text/html";
content_by_lua_file /home/openresty/nginx/conf/test_init.lua;
}
init.lua
--初始化耗时的模块
local redis = require 'resty.redis'
local cjson = require 'cjson'
--全局变量,不推荐
count = 1
--共享全局内存
local shared_data = ngx.shared.shared_data
shared_data:set("count", 1)
test_init.lua
count = count + 1
ngx.say("global variable : ", count)
local shared_data = ngx.shared.shared_data
ngx.say(", shared memory : ", shared_data:get("count"))
shared_data:incr("count", 1)
ngx.say("hello world")
注意一定在生产环境开启lua_code_cache
,否则每个请求都会创建Lua的VM实例
init_worker_by_lua
用于启动一些定时任务,比如心跳检查,定时拉取服务器配置等等;此处的任务是跟Worker进程数量有关系的,比如有2个Worker进程那么就会启动两个完全一样的定时任务
nginx的http部分
init_worker_by_lua_file /home/openresty/nginx/conf/init_worker.lua;
init_worker.lua
local count = 0
local delayInSeconds = 3
local heartbeatCheck = nil
heartbeatCheck = function(args)
count = count + 1
ngx.log(ngx.ERR, "do check ", count)
local ok, err = ngx.timer.at(delayInSeconds, heartbeatCheck)
if not ok then
ngx.log(ngx.ERR, "failed to startup heartbeart worker...", err)
end
end
heartbeatCheck()
error日志中
2019/08/21 17:25:21 [error] 27153#0: *1 [lua] init_worker.lua:7: heartbeatCheck(): do check 1, context: init_worker_by_lua*
2019/08/21 17:25:24 [error] 27153#0: *2 [lua] init_worker.lua:7: do check 2, context: ngx.timer
2019/08/21 17:25:27 [error] 27153#0: *3 [lua] init_worker.lua:7: do check 3, context: ngx.timer
2019/08/21 17:25:30 [error] 27153#0: *4 [lua] init_worker.lua:7: do check 4, context: ngx.timer
2019/08/21 17:25:33 [error] 27153#0: *5 [lua] init_worker.lua:7: do check 5, context: ngx.timer
2019/08/21 17:25:36 [error] 27153#0: *6 [lua] init_worker.lua:7: do check 6, context: ngx.timer
ngx.timer.at
:延时调用相应的回调方法;ngx.timer.at(秒单位延时,回调函数,回调函数的参数列表);可以将延时设置为0即得到一个立即执行的任务,任务不会在当前请求中执行不会阻塞当前请求,而是在一个轻量级线程中执行。
另外根据实际情况设置如下指令
lua_max_pending_timers 1024
; #最大等待任务数lua_max_running_timers 256
; #最大同时运行任务数
set_by_lua
set_by_lua_file
中的执行速度要快,不要阻塞
nginx配置
location /lua_set_1 {
default_type "text/html";
set_by_lua_file $num /home/openresty/nginx/conf/test_set_1.lua;
echo $num;
}
lua配置
local uri_args = ngx.req.get_uri_args()
local i = uri_args["i"] or 0
local j = uri_args["j"] or 0
return i + j
请求测试
$ curl "127.0.0.1:81/lua_set_1?i=1&j=10"
11
或者根据不同的url请求不同的后端
set_by_lua $to_book '
local ngx_match = ngx.re.match
local var = ngx.var
local skuId = var.skuId
local r = var.item_dynamic ~= "1" and ngx.re.match(skuId, "^[0-9]{8}$")
if r then return "1" else return "0" end;
';
set_by_lua $to_mvd '
local ngx_match = ngx.re.match
local var = ngx.var
local skuId = var.skuId
local r = var.item_dynamic ~= "1" and ngx.re.match(skuId, "^[0-9]{9}$")
if r then return "1" else return "0" end;
';
#自营图书
if ($to_book) {
proxy_pass http://127.0.0.1/old_book/$skuId.html;
}
#自营音像
if ($to_mvd) {
proxy_pass http://127.0.0.1/old_mvd/$skuId.html;
}
#默认
proxy_pass http://127.0.0.1/proxy/$skuId.html;
rewrite_by_lua
nginx配置
location /lua_rewrite_1 {
default_type "text/html";
rewrite_by_lua_file /home/openresty/nginx/conf/test_rewrite_1.lua;
echo "no rewrite";
}
test_rewrite_1.lua
代码
if ngx.req.get_uri_args()["jump"] == "1" then
return ngx.redirect("http://www.jd.com?jump=1", 302)
end
测试请求
$ curl -I 127.0.0.1:81/lua_rewrite_1?jump=1
HTTP/1.1 302 Moved Temporarily
Server: openresty/1.15.8.1
Date: Wed, 21 Aug 2019 10:13:24 GMT
Content-Type: text/html
Content-Length: 151
Connection: keep-alive
Location: http://www.whysdomain.com?jump=1
$ curl -I 127.0.0.1:81/lua_rewrite_1
HTTP/1.1 200 OK
Server: openresty/1.15.8.1
Date: Wed, 21 Aug 2019 10:13:36 GMT
Content-Type: text/html
Connection: keep-alive
nginx配置
location /lua_rewrite_2 {
default_type "text/html";
rewrite_by_lua_file /home/openresty/nginx/conf/test_rewrite_2.lua;
echo "rewrite2 uri : $uri, a : $arg_a";
}
test_rewrite_2.lua
代码
if ngx.req.get_uri_args()["jump"] == "1" then
ngx.req.set_uri("/lua_rewrite_3", false);
ngx.req.set_uri("/lua_rewrite_4", false);
ngx.req.set_uri_args({a = 1, b = 2});
end
进行测试
$ curl 127.0.0.1:81/lua_rewrite_2?jump=0
rewrite2 uri : /lua_rewrite_2, a :
$ curl
rewrite2 uri : /lua_rewrite_4, a : 1
ngx.req.set_uri(uri, false)
:可以内部重写uri(可以带参数),等价于rewrite ^ /lua_rewrite_3
;通过配合if/else可以实现rewrite ^ /lua_rewrite_3 break;
这种功能;此处两者都是location内部url重写,不会重新发起新的location匹配;ngx.req.set_uri_args
:重写请求参数,可以是字符串(a=1&b=2)也可以是table;
nginx配置
location /lua_rewrite_3 {
default_type "text/html";
rewrite_by_lua_file /home/openresty/nginx/conf/test_rewrite_3.lua;
echo "rewrite3 uri : $uri";
}
test_rewrite_3.lua
代码
if ngx.req.get_uri_args()["jump"] == "1" then
ngx.req.set_uri("/lua_rewrite_4", true);
ngx.log(ngx.ERR, "=========")
ngx.req.set_uri_args({a = 1, b = 2});
end
ngx.req.set_uri(uri, true)
:可以内部重写uri,即会发起新的匹配location请求,等价于rewrite ^ /lua_rewrite_4 last
;此处看error log是看不到我们记录的log。
测试请求
$ 127.0.0.1:81/lua_rewrite_3?jump=1
global variable : 2 , shared memory : 1 hello world
此处没有/lua_rewrite_4
,所以匹配到默认的请求
即
rewrite ^ /lua_rewrite_3;等价于ngx.req.set_uri("/lua_rewrite_3", false);
rewrite ^ /lua_rewrite_3 break;等价于ngx.req.set_uri("/lua_rewrite_3", false); 加if/else判断/break/return
rewrite ^ /lua_rewrite_4 last;等价于ngx.req.set_uri("/lua_rewrite_4", true);
注意,在使用rewrite_by_lua
时,开启rewrite_log on;
后也看不到相应的rewrite log。
access_by_lua
nginx配置
location /lua_access {
default_type "text/html";
access_by_lua_file /home/openresty/nginx/conf/test_access.lua;
echo "access";
}
test_access.lua代码
if ngx.req.get_uri_args()["token"] ~= "123" then
return ngx.exit(403)
end
测试请求
$ curl 127.0.0.1:81/lua_access?token=why
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>openresty/1.15.8.1</center>
</body>
</html>
$ curl 127.0.0.1:81/lua_access?token=123
access