如何通过 Lua 扩展 Nginx

发布时间:2021-07-10 10:31:01 作者:chen
来源:亿速云 阅读:166

这篇文章主要讲解了“如何通过 Lua 扩展 Nginx”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“如何通过 Lua 扩展 Nginx”吧!

1. ngx_lua 模块


2. 协程(Coroutine)


1. 协程类似一种多线程,与多线程的区别

Nginx 的每个 Worker 进程都是在 epoll 或 kqueue 这样的事件模型之上,封装成协程,每个请求都有一个协程进行处理。这正好与 Lua 内建协程的模型是一致的,所以即使 ngx_lua 需要执行 lua,相对 C 有一定的开销,但依然能保证高并发能力。

3. Nginx 进程模型


1. Master 进程具体包括如下 4 个主要功能
2. 进程模型

如何通过 Lua 扩展 Nginx

4. HTTP 请求处理


阶段说明
post-read读取请求内容阶段,nginx 读取并解析完请求头之后就立即开始运行
server-rewriteserver 请求地址重写阶段
find-config配置查找阶段,用来完成当前请求与 location 配置块之间的配置工作
rewritelocation 请求地址重写阶段,当 ngx_rewrite 指令用于 location 中,就是在这个阶段运行的
post-rewrite请求地址重写阶段,当 nginx 完成 rewrite 阶段所要求的内部跳转动作,如果 rewrite 阶段有这个要求的话
preaccess访问权限检查准备阶段,ngx_limit_req 和 ngx_limit_zone 在这个阶段运行,ngx_limit_req 可以控制请求的访问频率,ngx_limit_zone 可以控制访问的并发度。
access权限检查阶段,ngx_access 在这个阶段运行,配置指令多是执行访问控制相关的任务,入检查用户的访问权限,检查用户的来源 IP 是否合法
post-access访问权限检查提交阶段
try-files配置 try_files 处理阶段
content内容产生阶段,是所有请求处理阶段中最为重要的阶段,因为这个阶段的指令通常是用来生成 HTTP 响应内容的
log日志模块处理阶段

5. ngx_lua 指令


指令所处处理阶段使用范围解释
init_by_lua<br/>init_by_lua_fileloading-confighttpnginx Master 进程加载配置时执行;<br/>通常用于初始化全局配置/预加载 Lua 模块
init_worker_by_lua<br/>init_worker_by_lua_filestarting-workerhttp每个 Nginx Worker 进程启动时调用的计时器,如果 Master 进程不允许<br/>则只会在 init_by_\lua 之后调用;通常用于定时拉取配置/数据,<br/>或者后端服务的健康检查。
set_by_lua<br/>set_by_lua_filerewriteserver,server if,location,location if设置 nginx 变量,可以实现复杂的赋值逻辑;此处是阻塞的,Lua 代码要做到非常快
write_by_lua<br/>rewrite_by_lua_filerewrite tailhttp,server,location,location ifrewrite 阶段处理,可以实现复杂的转发/重定向逻辑。
access_by_lua<br/>access_by_lua_fileaccess tailhttp,server,location,location if请求访问阶段处理,用于访问控制
content_by_lua<br/>content_by_lua_filecontentlocation,location if内容处理器,接受请求处理并输出响应
header_filter_by_lua<br/>header_filter_by_lua_fileoutput-header-firsthttp,server,location,location if设置 header 和 cookie
body_filter_by_lua<br/>body_filter_by_lua_fileoutput-body-filterhttp,server,location,location if对响应数据进行过滤,比如截断、替换
log_by_lua<br/>log_by_lua_fileloghttp,server,location,location iflog 阶段处理,比如记录访问量/统计平均响应时间

6. OpenResty


1. 概念
2. 工作原理
3. 目标

7. ngx_lua 实例


1. 简单示例
user www-data;
worker_processes auto;
pid /run/nginx.pid;

error_log logs/error.log;

events {
    worker_connections 1024;
}

http {
    server {
        listen 8080;
        location / {
            default_type text/html;
            content_by_lua '
                ngx.say("<p>Hello, world!</p>")
            ';
        }
    }

}
user www-data;
worker_processes auto;
pid /run/nginx.pid;

error_log logs/error.log;

events {
    worker_connections 1024;
}

http {
    server {
        listen 8080;
        location / {
            default_type text/html;
            content_by_lua_block {
                ngx.say('Hello, world!')
            }
        }
    }

}
启动
/usr/local/openresty/nginx/sbin/nginx -p `pwd` -c conf/nginx_openresty_01.conf

测试
curl -i http://127.0.0.1/
2. 休眠示例
user www-data;
worker_processes auto;
pid /run/nginx.pid;

error_log logs/error.log;

events {
    worker_connections 1024;
}

http {
    server {
        listen 8080;
        location /lua_1 {
            default_type text/html;
            content_by_lua_block {
                ngx.say('Hello, world! @ Time 1!')
                ngx.sleep(3)
                ngx.say('Hello, world! @ Time 2!')
            }
        }
    }

}
启动
/usr/local/openresty/nginx/sbin/nginx -p `pwd` -c conf/nginx_openresty_02.conf

测试
curl -i http://127.0.0.1/lua_1
curl -i http://127.0.0.1/lua_1
3. 带参数示例
user www-data;
worker_processes auto;
pid /run/nginx.pid;

error_log logs/error.log;

events {
    worker_connections 1024;
}

http {
    server {
        listen 8080;
        location /lua_1 {
            default_type text/html;
            content_by_lua_block {
                ngx.say(ngx.var.arg_a)
            }
        }
    }

}
启动
/usr/local/openresty/nginx/sbin/nginx -p `pwd` -c conf/nginx_openresty_03.conf

测试
curl -i http://127.0.0.1?a=nginx_lua

8. OpenResty 连接 redis


配置文件
user www-data;
worker_processes auto;
pid /run/nginx.pid;

error_log logs/error.log;

events {
    worker_connections 1024;
}

http {
    server {
        listen 8080;
        location ~/redis_lua/(\d+)$ {
            default_type text/html;
            charset utf-8;
            lua_code_cache on;
            content_by_lua_file '/home/zp/openresty/lua/redis.lua';
        }
    }

}
lua 脚本
local json = require("cjson")
local redis = require("resty.redis")
local red = redis:new()
red:set_timeout(1000)
local ip = "127.0.0.1"
local port = 6379
local ok, err = red:connect(ip, port)
if not ok then
    ngx.say('connect to redis error: ', err)
    return ngx.exit(500)
end

local id = ngx.var[1]
local value = "calue-"..id

red:set(id, value)

local resp, err = red:get(id)

if not resp then
    ngx.say('get from redis error: ', err)
    return ngx.exit(500)
end

red:close()

ngx.say(json.encode({content=resp}))
测试
启动
/usr/local/openresty/nginx/sbin/nginx -p `pwd` -c conf/nginx_openresty_04.conf

测试
curl -i http://127.0.0.1/redis_lua/1
curl -i http://127.0.0.1/redis_lua/2
curl -i http://127.0.0.1/redis_lua/3

感谢各位的阅读,以上就是“如何通过 Lua 扩展 Nginx”的内容了,经过本文的学习后,相信大家对如何通过 Lua 扩展 Nginx这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. 如何通过jenkins和nginx构建发布网站
  2. 通过nginx反向代理来调试代码的实现

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

lua nginx

上一篇:Android辅助功如何实现自动抢红包

下一篇:Java中PhantomJs如何完成html图片输出功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》