OpenResty 是一个基于 Nginx 与 Lua 的高性能 Web 平台,其内部集成了大量精良的 Lua 库、第三方模块以及大多数的依赖项。用于方便地搭建可以处理超高并发、扩展性极高的动态 Web 应用、Web 服务和动态网关。html
Lua是一个简洁、轻量、可扩展的程序设计语言,其设计目的是为了嵌入应用程序中,从而为应用程序提供灵活的扩展和定制功能。Lua由标准C编写而成,代码简洁优美,几乎在全部操做系统和平台上均可以编译,运行。nginx
1.安装依赖库git
yum install readline-devel pcre-devel openssl-devel gcc
2.下载及安装OpenRestygithub
wget https://openresty.org/download/openresty-1.9.15.1.tar.gz tar xvf openresty-1.9.15.1.tar.gz cd openresty-1.9.15.1 ./configure --with-luajit && make && make install
激活LuaJIT浏览器
组件被用于构建 OpenResty。全部的组件能够被激活或禁止。 大部组件默认是激活的,也有部件不是。 LuaJIT、 DrizzleNginxModule、PostgresNginxModule和IconvNginxModule 默认是没有激活的。您须要经过如下选项在编译 OpenResty的时候将它们各自激活, --with-luajit、 --with-http_drizzle_module、 --with-http_postgres_module和 --with-http_iconv_module 。并发
安装好的OpenRestyapp
从上图能够看到,openresty在/usr/local目录下高并发
经过下述方式启动Nginx。若是没有任何输出,说明启动成功,-p 指定咱们的项目目录,-c 指定配置文件。post
/usr/local/openresty/nginx/sbin/nginx -c /usr/local/openresty/nginx/conf/nginx.conf /usr/local/openresty/nginx/sbin/nginx -p 'pwd' -c /usr/local/openresty/nginx/conf/nginx.conf
为openresty下的nginx创建软链(非必需)性能
ln -s /usr/local/openresty/nginx/sbin/nginx /usr/sbin/nginx
则可以使用以下方式启动
/usr/sbin/nginx -c /usr/local/openresty/nginx/conf/nginx.conf
在浏览器中访问:
因为原生的Nginx日志没有resp_body这一选项,经过在nginx.conf中添加Lua脚本的方式定义resp_body。
http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; log_format log_resp_body '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for" ' '$request_time $bytes_sent $request_length "$request_body" "$resp_body"'; access_log logs/access.log main; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; access_log logs/access.index.log log_resp_body; lua_need_request_body on; set $resp_body ""; body_filter_by_lua ' local resp_body = string.sub(ngx.arg[1], 1, 1000) ngx.ctx.buffered = (ngx.ctx.buffered or "") .. resp_body if ngx.arg[2] then ngx.var.resp_body = ngx.ctx.buffered end '; location / { root html; index index.html index.htm; } # redirect server error pages to the static page /50x.html error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
检测Nginx配置是否正确
/usr/sbin/nginx -t
重启Nginx
/usr/sbin/nginx -s reload
验证Lua配置是否成功
tail -f access.log
tail -f access.index.log
参考资料:
OpenResty
OpenResty中文站
nginx-lua
lua-nginx-module
实践证实,上面body_filter_by_lua中的代码存在bug,可经过以下方式更正:
body_filter_by_lua ' local maxlen = 1000 ngx.ctx.buffered = ngx.ctx.buffered or "" if #ngx.ctx.buffered < maxlen then ngx.ctx.buffered = ngx.ctx.buffered .. string.sub(ngx.arg[1], 1, maxlen - #ngx.ctx.buffered) end if ngx.arg[2] then ngx.var.resp_body = ngx.ctx.buffered end ';