本文演示OpenResty应用中编写自己的 Lua 模块
1. 创建项目
创建项目结构
cd ~
mkdir demo
cd demo
mkdir conf
mkdir lua
mkdir logs
touch conf/nginx.conf
创建完项目结构如下
创建Lua模块
创建简单的lua模块文件
touch lua/test.lua
文件内容如下:
local _M = {}
function _M.test(name)
ngx.log(ngx.INFO, 'test lua module')
ngx.say('this from test.lua: ' .. name)
end
return _M
编写nginx配置文件
vi conf/nginx.conf
worker_processes 1;
error_log logs/error.log info;
events {
worker_connections 128;
}
http {
# 指定加载的lua模块路径($prefix 由启动脚本指定)
lua_package_path "$prefix/lua/?.lua;;";
init_worker_by_lua_block {
ngx.log(ngx.INFO, "init_worker_by_lua_block worker.id=", ngx.worker.id())
if 0 == ngx.worker.id() then
ngx.log(ngx.INFO, "do something")
end
}
server {
listen 8080;
location / {
default_type text/html;
content_by_lua_block {
local hello = require "test"
hello.test('xx');
}
}
}
}
启动
# 配置检查,指定$prefix
nginx -p `pwd`/ -t
# 启动
nginx -p `pwd`/
# 验证
curl http://127.0.0.1:8080/
#:this from test.lua: xx
如有问题可查看log文件夹下的日志文件。