本文摘自PHP中文网,作者(*-*)浩,侵删。
lua是一个巴西人设计的小巧的脚本语言,它的设计目的是为了能够嵌入到应用程序中,从而为应用程序提供灵活的扩展和定制功能。

淘宝的agentzh和chaoslawful开发的ngx_lua模块通过将lua解释器集成进Nginx。这个模块会在每个nginx的worker_process中启动一个lua解释器,在nginx处理http请求的11个阶段中,你可以在其中的多个阶段用lua代码处理请求。能够采用lua脚本实现业务逻辑,因为lua的紧凑、高速以及内建协程,所以在保证高并发服务能力的同一时候极大地减少了业务逻辑实现成本。
实例:解决服务稳定性
这里的思路很简单,我们会在error_page指令被执行后,用lua代码来接受参数,处理逻辑部分,最终会返回前端和用php处理看起来一致的内容。
部分代码如下:
nginx_conf:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | location ~* ^/api/.+/.+$ {
error_page 500 502 503 504 =200 @jump_to_error_page_api;
rewrite ^/api/(.+)/(.+)$ /index.php?_c= $1 &_a= $2 break ;
root /home/ligang/demo/src/api/;
fastcgi_pass 127.0.0.1:9000;
include fastcgi.conf;
fastcgi_connect_timeout 5s;
fastcgi_send_timeout 5s;
fastcgi_read_timeout 5s;
fastcgi_intercept_errors on;
}
location @jump_to_error_page_api {
lua_code_cache on; set $prj_home " /home/ligang/demo" ;
content_by_lua_file /home/ligang/demo/src/glue/error_page_api.lua;
}
|
这里大家看到,当请求出现50x错误时,会跳到location jump_to_error_page_api中,在这里面,content_by_lua_file指令会在content处理阶段启动指定好的lua脚本(这里是error_page_api.lua)来处理请求。
我们再看下lua脚本中都做了什么:
lua示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | ngx.header[ 'Content-Type' ] = 'text/html'
prj_home = ngx. var .prj_home
request_args = ngx.req.get_uri_args()
local controller = request_args[ '_c' ]
local action = request_args[ '_a' ]
if 'demo' == controller
then
processErrorPageApiDemo(action)
else
ngx. print ( 'invalid controller' )
end
......
|
这里大家可以看到,我们可以在lua脚本中接受请求参数,做和php一样的逻辑,最终输出前端需要的正确的内容。
目前这套机制我们已经用在我们这边的一个重要用户页面上,目前都没有收到用户反馈说页面打不开,出现错误页这种,效果很是明显。
更多Nginx相关技术文章,请访问Nginx使用教程栏目进行学习!
以上就是nginx_lua能做什么的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
nginx的三种反向代理方式你都知道么
编译安装nginx却requires the pcre library
nginx安装ssl证书的正确方法
执行nginx命令提示找不到命令怎么解决
linux中nginx反向代理下的tomcat集群的详解
如何修改nginx服务的默认端口
linux下安装nginx的正确方法
nginx在做负载均衡时如何配置文件
nginx文件在哪里
apache与nginx哪个好
更多相关阅读请进入《nginx》频道 >>
转载请注明出处:木庄网络博客 » nginx_lua能做什么