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

openresty 好用的框架(在MacOS上安装OpenResty的开发环境)(1)

安装OpenResty

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

brew install openresty/brew/openresty

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

openresty -V nginx -V

测试安装

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

mkdir openresty mkdir openresty/conf mkdir openresty/log

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

worker_processes 1; error_log log/error.log; events { worker_connections 1024; } http { server { listen 8080; location / { default_type text/html; content_by_lua_block { ngx.say("<h2>hello</h2>") } } } }

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

cd openresty nginx -p ./ -c conf/nginx.conf ps -ef | grep nginx nginx: master process nginx -p ./ -c conf/nginx.conf nginx: worker process

使用curl测试访问:

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

测试后停止nginx服务:

nginx -p ./ -s stop

OpenResty的CLI

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

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

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

进一步工程化

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

ngx.say("hello!")

修改conf目录下的nginx.conf:

worker_processes 1; error_log log/error.log; events { worker_connections 1024; } lua_code_cache http { server { listen 8080; location / { default_type text/html; content_by_lua_file lua/hello.lua; } } }

启动nginx进行测试:

nginx -p ./ -c conf/nginx.conf curl 127.0.0.1:8080 hello!

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

worker_processes 1; error_log log/error.log; events { worker_connections 1024; } http { server { listen 8080; lua_code_cache off; location / { default_type text/html; content_by_lua_file lua/hello.lua; } } }

参考,