OpenResty是一个基于 Nginx与 Lua的高性能Web平台,其内部集成了大量精良的Lua库、第三方模块以及大多数的依赖项。 用于方便地搭建能够处理超高并发、扩展性极高的动态Web应用、Web 服务和动态网关。Nginx及其模块是使用C语言开发的,为了能够在Nginx之上写业务代码,需要借助OpenResty在Nginx上Lua语言开发业务逻辑。 Lua是单线程多协程(coroutine)的并发模型,与Nginx的多进程单线程+多路IO复用的并发事件驱动模型很配。本文将学习在MacOS下搭建OpenResty的开发环境。

安装OpenResty

在MacOS下使用brew安装OpenResty,命令如下:

1brew install openresty/brew/openresty

安装完成后,将/usr/local/Cellar/openresty/<version>/bin/usr/local/Cellar/openresty/<version>/nginx/sbin配置到系统的PATH环境变量中,并进行一下测试,确保能够正常打印版本信息:

1openresty -V
2nginx -V

测试安装

创建本地项目目录,这里假设为operesty:

1mkdir openresty
2mkdir openresty/conf
3mkdir openresty/log

在conf目录下创建一个nginx.conf文件,内部代码如下:

 1worker_processes 1;
 2error_log log/error.log;
 3
 4events {
 5    worker_connections 1024;
 6}
 7
 8http {
 9    server {
10        listen 8080;
11        location / {
12            default_type text/html;
13            content_by_lua_block {
14                ngx.say("<h2>hello</h2>")
15            }
16        }
17    }
18}

使用下面的命令在后台启动nginx服务,启动后使用ps命令可以查看nginx的master和worker进程:

1cd openresty
2nginx -p ./ -c conf/nginx.conf
3
4ps -ef | grep nginx
5nginx: master process nginx -p ./ -c conf/nginx.conf 
6nginx: worker process

使用curl测试访问:

1curl 127.0.0.1:8080
2<h2>hello</h2>

测试后停止nginx服务:

1nginx -p ./ -s stop

OpenResty的CLI

前面测试安装时,我们创建一个项目目录,颇有点“工程化”的味道。 还可以使用OpenResty的CLI工具进行一下测试,resty是OpenResty的CLI工具,其本身是一个1000多行的perl脚步。

下面使用resty进行一下helloword的测试:

1resty -e "ngx.say('hello')"
2hello

进一步工程化

下面将lua代码从nginx.conf中提取到外部单独的lua文件中以便于维护,在项目目录与conf目录同级创建一个lua的目录,在该目录中 创建hello.lua文件:

1ngx.say("hello!")

修改conf目录下的nginx.conf:

 1worker_processes 1;
 2error_log log/error.log;
 3
 4events {
 5    worker_connections 1024;
 6}
 7
 8lua_code_cache
 9
10http {
11    server {
12        listen 8080;
13        location / {
14            default_type text/html;
15            content_by_lua_file lua/hello.lua;
16        }
17    }
18}

启动nginx进行测试:

1nginx -p ./ -c conf/nginx.conf
2
3curl 127.0.0.1:8080
4hello!

Lua代码在第一个请求时会被加载并默认缓存,因此每次修改Lua源代码文件后需要重新加载OpenResty。 在开发调试时建议在nginx.conf中关闭lua_code_cache,但这会影响性能,在正式环境中应该保持打开。

 1worker_processes 1;
 2error_log log/error.log;
 3
 4events {
 5    worker_connections 1024;
 6}
 7
 8http {
 9    server {
10        listen 8080;
11        lua_code_cache off;
12        location / {
13            default_type text/html;
14            content_by_lua_file lua/hello.lua;
15        }
16    }
17}

参考