下面是我阅读春哥OpenResty官网主页中“Using LuaRocks”一节的实操记录,整理如下。
https://openresty.org/cn/using-luarocks.html
1.在CentOS 6.9 x86_64搭建Lua开发环境
详细过程参见本博博文
http://www.jb51.cc/article/p-ylsveqwv-bro.html
2.通过LuaRocks安装 Lua MD5 库@H_403_15@ 在本示例中,我们将使用Lua MD5 library作为服务器上的一个例子,所以我们需要通过LuaRocks来安装它:@H_403_15@ luarocks install md5
3.配置我们的OpenResty应用@H_403_15@ vim Nginx.conf@H_403_15@ 添加以下内容
worker_processes 1; # we could enlarge this setting on a multi-core machine user root; error_log logs/error.log warn; events { worker_connections 1024; } http { #must use absolute path lua_package_path '/root/or_test/conf/using_luarocks/?.lua;;'; server { listen 80; server_name localhost; location = /luarocks { #rewrite_by_lua_file "conf/using_luarocks/foo.lua"; content_by_lua ' local foo = require("foo") foo.say("hello,luarocks!") --ngx.say("Hello world!") '; } } }
我们希望最终的目录结构如下@H_403_15@ @H_403_15@ @H_403_15@ 创建与conf下面的using_luarocks子文件夹存放lua文件@H_403_15@ mkdir -p /root/or_test/conf/using_luarocks@H_403_15@ 存入foo.lua@H_403_15@
module("foo",package.seeall) local bar = require "bar" ngx.say("bar loaded") function say (var) bar.say(var) end存入bar.lua @H_403_15@
module("bar",package.seeall) local rocks = require "luarocks.loader" local md5 = require "md5" ngx.say("rocks and md5 loaded") function say (a) ngx.say(md5.sumhexa(a)) end@H_403_15@ 4.开启Nginx服务 @H_403_15@ 首先测试配置文件合法性 @H_403_15@ Nginx -p ~/or_test -c ~/or_test/conf/using_luarocks.conf -t @H_403_15@ 重启OpenResty服务 @H_403_15@ Nginx -p ~/or_test -c ~/or_test/conf/using_luarocks.conf -s reload @H_403_15@ 查看进程是否正常 @H_403_15@ ps auxf | grep Nginx @H_403_15@ 查看端口是否启动 @H_403_15@ netstat -ntlp @H_403_15@ @H_403_15@ @H_403_15@ 5.测试我们的应用 @H_403_15@ 现在我们通过curl 工具或者任意兼容HTTP协议的浏览器测试我们的应用: @H_403_15@ curl -v http://localhost/luarocks @H_403_15@ 我们在第一次运行的时候得到以下的内容: @H_403_15@ rocks and md5 loaded @H_403_15@ bar loaded @H_403_15@ 85e73df5c41378f830c031b81e4453d2
@H_403_15@ 第二次运行的时候得到以下内容:@H_403_15@ 85e73df5c41378f830c031b81e4453d2@H_403_15@ @H_403_15@ @H_403_15@ 6.基准测试@H_403_15@ 现在,让我们来做一些基准测试吧:@H_403_15@ ab -c10 -n50000 http://127.0.0.1/luarocks@H_403_15@ 测试在是我的CentOS 6.9 x86_64虚拟机上进行的,下面是测试中产生的数据@H_403_15@ @H_403_15@ @H_403_15@ @H_403_15@ 7.特殊说明@H_403_15@ 这里OpenResty默认包含了LuaJIT,系统中没有完整的lua程序,我使用源码安装了完整的lua,并继续安装了模块管理工具LuaRocks,@H_403_15@ 使用LuaRocks去安装其它lua相关的模块(OpenResty中没有包含的),并通过在Nginx.conf中引用这些lua脚本来实现一些业务需求,比如这里的md5模块。这个思路是可行的。
@H_403_15@ 8.参考文献 [1].https://openresty.org/cn/using-luarocks.html