openresty lua 模块
一个业务逻辑可能会非常复杂,不可能将所有的逻辑写到一个文件中,这就需要模块的概念。将公共方法抽取成为一个模块,在使用时可以调用这个模块的方法。lua中的模块有点类似于Java中类的抽象层级,但和类又有本质差别。
定义一个模块 创建一个lua文件 test_module.lua,内容如下
local count = 0
local function hello()
count = count + 1
ngx.say("count : ", count)
end
local _M = {
hello = hello
}
return _M
引入模块
1.在nginx.conf 中http模块下指定模块代码存放的路径
lua_package_path "/lua/lualib/?.lua;;"; #lua 模块
lua_package_cpath "/lua/lualib/?.so;;"; #c模块
2.在lua代码中引用需要的模块
local testModule = require("test_module")
调用模块方法
testModule.hello();