一、指令顺序
nginx配置文件中执行lua语句是通过指令来识别的,lua指令执行顺序如下:
二、init_by_lua_file代码诠释
init_by_lua*
是 OpenResty 目前唯一运行在 master 进程里的阶段。它运行的时机非常靠前,就在 Nginx 刚解析完配置之后。
init_by_lua_file在ngx启动时(加载配置文件)主要用来执行加载比较耗时的操作、做一些全局化工作。这里通过一个例子来说明:我们在ngx中开辟一个全局变量,并在lua中执行自增操作。
1、nginx.conf 的http中写入:
在最后两行,主要意思:
1)、利用lua_shared_dict定义一个共享内存,内存大小为1m。如果 shdict 里面的数据超过了事先分配好的内存大小限制,OpenResty 会根据 LRU 算法,清除现有的数据
2)、init_by_lua_file 指定lua的文件位置,这里一般用来执行一些加载比较耗时的操作,比如连接数据库等。
http {
#include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log logs/access.log main;
sendfile off;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
lua_shared_dict shared_data 1m;
init_by_lua_file "/Users/stefan/mac_develep/nginx/lua/init.lua";
2、init.lua的内容:
--load module that spend time
local redis = require "resty.redis"
local cjson = require "cjson"
--global var
count = 1
--
--get share data from ngx
local share_data = ngx.shared.shared_data
share_data:set("count", 1)
3、增加content.lua测试
--opentor count
count = count + 1
--
ngx.say("gloabl var:", count)
ngx.say("end.....")
4、增加location配合测试
location /lua {
default_type "application/json";
content_by_lua_file "/Users/stefan/mac_develep/nginx/lua/content.lua";
#echo $num;
}
5、执行:curl http://localhost:808/lua
stefan@StefandeMacBook-Pro lua % curl http://localhost:808/lua
gloabl var:2
end.....
三、init_worker_by_lu_file 详解
用于启动一些定时任务,比如心跳检查,定时拉取服务器、数据库数据等。我主要是想在这里来定时获取redis配置。
1、在http 模块下加入:
init_worker_by_lua_file "/Users/stefan/mac_develep/nginx/lua/init_work.lua"
2、init_work.lua 写入:
--we can get conf from redis on time
local count = 0
local delay_times = 3
local heart_beat_check = nil
heart_beat_check = function()
count = count + 1
ngx.log(ngx.ERR, "do check", count)
local ok, err = ngx.timer.at(delay_times, heart_beat_check)
if not ok then
ngx.log(ngx.ERR, "failed to heart beat.", err)
end
end
--start function
heart_beat_check()
reload nginx 后,nginx的err日志会不断的打印:
2020/02/27 10:31:38 [error] 45272#0: *910 [lua] init_work.lua:8: do check857, context: ngx.timer
2020/02/27 10:31:41 [error] 45272#0: *911 [lua] init_work.lua:8: do check858, context: ngx.timer
2020/02/27 10:31:44 [error] 45272#0: *912 [lua] init_work.lua:8: do check859, context: ngx.timer