Home > Backend Development > PHP Tutorial > Ngx_Lua usage sharing

Ngx_Lua usage sharing

WBOY
Release: 2016-08-08 09:29:27
Original
1743 people have browsed it

  1. Nginx_Lua
    • 1.1. Introduction
    • 1.2. Installation
      • 1.2.1. Install JIT platform
      • 1.2.2. NDK and Lua_module
      • 1.2.3. Compile and install Nginx
    • 1.3. After embedding Lua
      • 1.3.1. Detection version
      • 1.3.2. Hello, World
      • 1.3.3. Synchronous form, asynchronous execution
    • 1.4. Nginx and Lua execution sequence
      • 1.4.1. Nginx order
      • 1.4.2. Lua order
  2. Lua basic syntax
    • 2.1. Keywords
    • 2.2. Operations
      • 2.2.1. Number operations
      • 2.2.2. Assignment operations
      • 2.2.3. Logical operations
    • 2.3. Conditional judgment statements
      • 2.3.1. if
      • 2.3.2. repeat
      • 2.3.3. while
      • 2.3.4. for
    • 2.4. Common structures
      • 2.4.1. table
      • 2.4.2. Lua table empty judgment
    • 2.5. Reference

1. Nginx_Lua

1.1. Introduction

ngx_lua - Lua language is embedded in nginx, Make it support Lua to quickly develop business logic based on nginx

This module is not in the nginx source code package and needs to be downloaded, compiled and installed by yourself. Use lua 5.1 (lua 5.2 is not currently supported) or luajit 2.0.

After adding Lua support, complex modules can be developed with fast cycle times and are still 100% asynchronous and non-blocking.

ngx_lua Who is using it:

Taobao, Tencent Finance, NetEase Finance, 360, Qunar.com, etc.

CloudFlare, CNN, Wingify, Reblaze, Turner, Broadcasting System

Main developer of this project:

chaoslawful Taobao .

通常,程序有两种运行方式:静态编译与动态直译。 静态编译的程序在执行前全部被翻译为机器码,而动态直译执行的则是一句一句边运行边翻译。 即时编译(Just-In-Time Compiler)则混合了这二者,一句一句编译源代码,但是会将翻译过的代码缓存起来以降低性能损耗。 JAVA、.NET 实现都使用即时编译以提供高速的代码执行。 注意: 在nginx.conf中添加"lua_code_cache on/off",来开启是否将代码缓存,所以每次变更"*.lua"文件时,必须reload nginx才可生效。 仅针对"set_by_lua_file, content_by_lua_file, rewrite_by_lua_file, and access_by_lua_file"有效, 因为其他为写在配置文件 中,更改代码也必须reload nginx。在生产环境下,不能禁用cache。同时在lua代码中使用"dofile" 或 "loadfie" 来加载外部lua脚步 将不会对它进行缓存,应该使用"require"来代替。禁用cache,当且仅当在调式代码下。 demo 1

Download and compile

是一个利用JIT编译技术把Lua脚本直接编译成机器码由CPU运行 版本:2.0 与 2.1 当前稳定版本为 2.0。 2.1为版本与ngx_lua将有较大性能提升,主要是CloudFlare公司对luajit的捐赠。 FFI库,是LuaJIT中最重要的一个扩展库。 1. 它允许从纯Lua代码调用外部C函数,使用C数据结构; 2. 就不用再像Lua标准math库一样,编写Lua扩展库; 3. 把开发者从开发Lua扩展C库(语言/功能绑定库)的繁重工作中释放出来; demo 2

1.2.2. NDK and Lua_module

NDK (Nginx Development Kit) module is a module that expands the core functions of the Nginx server

Third-party module development can be quickly implemented based on it

NDK Provide functions and macros to handle some basic tasks and reduce the amount of code developed by third-party modules.

wget -c http://luajit.org/download/LuaJIT-2.0.2.tar.gz tar xzvf LuaJIT-2.0.2.tar.gz cd LuaJIT-2.0.2 make install PREFIX=/usr/local/luajit echo "/usr/local/luajit/lib" > /etc/ld.so.conf.d/usr_local_luajit_lib.conf ldconfig #注意环境变量! export LUAJIT_LIB=/usr/local/luajit/lib export LUAJIT_INC=/usr/local/luajit/include/luajit-2.01.2.3. Compile and install Nginxwget -c https://github.com/simpl/ngx_devel_kit/archive/v0.2.18.tar.gz wget -c https://github.com/chaoslawful/lua-nginx-module/archive/v0.8.6.tar.gz tar xzvf v0.2.18 tar xzvf v0.8.6

1.3. After embedding Lua

1.3.1. Detect the versionwget -c http://nginx.org/download/nginx-1.4.2.tar.gz tar xzvf nginx-1.4.2.tar.gz cd nginx-1.4.2 ./configure --add-module=../ngx_devel_kit-0.2.18/ --add-module=../lua-nginx-module-0.8.6/ make make install

1.3.2. Hello, World

Add a location to the service in nginx.conf.

自己编译官方的 nginx 源码包,只需事前指定 LUAJIT_INC 和 LUAJIT_LIB 这两个环境变量。 验证你的 LuaJIT 是否生效,可以通过下面这个接口: location = /lua-version { content_by_lua ' if jit then ngx.say(jit.version) else ngx.say(_VERSION) end '; } demo 3 如果使用的是标准 Lua,访问 /lua-version 应当返回响应体 Lua 5.1 如果是 LuaJIT 则应当返回类似 LuaJIT 2.0.2 这样的输出。 不要使用标准lua,应当使用luajit, 后者的效率比前者高多了。 也可以直接用 ldd 命令验证是否链了 libluajit-5.1 这样的 .so 文件,例如: [root@limq5 sbin]# ldd nginx | grep lua libluajit-5.1.so.2 => /usr/local/luajit/lib/libluajit-5.1.so.2 (0x00007f48e408b000) [root@limq5 sbin]#

demo 4

Users accessing http://localhost/test will print out the "Hello World" content.

ngx.say is the interface exposed by lua to the module.

Similarly, there is ngx.log(ngx.DEBUG, ""), which can output debugging information in error.log.

In addition, external scripts can also be called, just like when we write php and jsp applications, business scripts are organized separately in .php or .jsp files

location = /test { content_by_lua ' ngx.say("Hello World") ngx.log(ngx.ERR, "err err err") '; }

The content of the hello.lua file is as follows: location = /test2 { content_by_lua_file conf/lua/hello.lua; }

The script here can As complex as you want, you can also use Lua's own library

List of available modules for lua:

http://luarocks.org/repositories/rocks/

Installation is similar to yum, it also has a warehouse:

luarocks install luafilesystem

Run After the above command, a "lfs.so" file will be compiled, copy the file to the LUA_PATH defined by nginx, and then reference the library to call its functions.

LUA_PATH:

lua_package_path '/opt/17173/nginx-ds/conf/lua/?.lua;;'

lua_package_cpath '/opt/17173/nginx-ds/conf/lua/lib/?.so; /usr/local/lib/?.?;;';

where ";;" represents the original search range.

demo 5

1.3.3. Synchronous form, asynchronous execution

We assume that multiple data sources need to be accessed at the same time, and the query has no dependencies, then we can issue requests at the same time

In this way, my total delay time, it is the time taken by the slowest of all my requests, not the superposition of all the original request times

ngx.say("Hello World")location = /api { content_by_lua ' local res1, res2, res3 = ngx.location.capture_multi{ {"/memc"}, {"/mysql"}, {"/postgres"} } ngx.say(res1.body, res2.body, res3.body) '; } demo 6

1.4. Nginx and Lua execution order

1.4.1. Nginx order

Nginx when processing each user request , are processed in sequence according to several different phases, rather than according to the order in the configuration file.

The process of Nginx request processing is divided into 11 stages. The order of execution is

post-read, server-rewrite, find-config, rewrite, post-rewrite, preaccess, access, post-access, try-files , content, log.

ngx.location.capture 无法跨server进行处理, 只能在同一个server下的不同location。post-read: 读取请求内容阶段 Nginx读取并解析完请求头之后就立即开始运行 例如模块 ngx_realip 就在 post-read 阶段注册了处理程序,它的功能是迫使 Nginx 认为当前请求的来源地址是指定的某一个请求头的值。server-rewrite Server请求地址重写阶段 当 ngx_rewrite 模块的set配置指令直接书写在 server 配置块中时,基本上都是运行在 server-rewrite 阶段find-config 配置查找阶段 这个阶段并不支持 Nginx 模块注册处理程序,而是由 Nginx 核心来完成当前请求与 location 配置块之间的配对工作。rewrite Location请求地址重写阶段 当 ngx_rewrite 模块的指令用于 location 块中时,便是运行在这个 rewrite 阶段。 另外,ngx_set_misc(设置md5、encode_base64等) 模块的指令,还有 ngx_lua 模块的 set_by_lua 指令和 rewrite_by_lua 指令也在此阶段。post-rewrite 请求地址重写提交阶段 由 Nginx 核心完成 rewrite 阶段所要求的“内部跳转”操作,如果 rewrite 阶段有此要求的话。preaccess 访问权限检查准备阶段 标准模块 ngx_limit_req 和 ngx_limit_zone 就运行在此阶段,前者可以控制请求的访问频度,而后者可以限制访问的并发度。access 访问权限检查阶段 标准模块 ngx_access、第三方模块 ngx_auth_request 以及第三方模块 ngx_lua 的 access_by_lua 指令就运行在这个阶段。 配置指令多是执行访问控制性质的任务,比如检查用户的访问权限,检查用户的来源 IP 地址是否合法post-access 访问权限检查提交阶段 主要用于配合 access 阶段实现标准 ngx_http_core 模块提供的配置指令 satisfy 的功能。 satisfy all(与关系) satisfy any(或关系)try-files 配置项try_files处理阶段 专门用于实现标准配置指令 try_files 的功能 如果前 N-1 个参数所对应的文件系统对象都不存在,try-files 阶段就会立即发起“内部跳转”到最后一个参数(即第 N 个参数)所指定的 URI.

Taobao has opened an nginx development manual, which contains a lot of useful information

http://tengine.taobao.org/book/

The author's Google forum:

https://groups .google.com/forum/#!forum/openresty

1.4.2. Lua sequence

Lua processing stages and usage scope under Nginx:

content 内容产生阶段 Nginx 的 content 阶段是所有请求处理阶段中最为重要的一个,因为运行在这个阶段的配置指令一般都肩负着生成“内容” 并输出 HTTP 响应的使命。log 日志模块处理阶段 记录日志

Please refer to the official documentation:

http://wiki.nginx .org/HttpLuaModule

2. Basic syntax of Lua

2.1. Keywords

init_by_lua http set_by_lua server, server if, location, location if rewrite_by_lua http, server, location, location if access_by_lua http, server, location, location if content_by_lua location, location if header_filter_by_lua http, server, location, location if body_filter_by_lua http, server, location, location if log_by_lua http, server, location, location if timer

2.2. Operations

2.2.1. Number operations

init_by_lua: 在nginx重新加载配置文件时,运行里面lua脚本,常用于全局变量的申请。 例如lua_shared_dict共享内存的申请,只有当nginx重起后,共享内存数据才清空,这常用于统计。 set_by_lua: 设置一个变量,常用与计算一个逻辑,然后返回结果 该阶段不能运行Output API、Control API、Subrequest API、Cosocket API rewrite_by_lua: 在access阶段前运行,主要用于rewrite access_by_lua: 主要用于访问控制,能收集到大部分变量,类似status需要在log阶段才有。 这条指令运行于nginx access阶段的末尾,因此总是在 allow 和 deny 这样的指令之后运行,虽然它们同属 access 阶段。 content_by_lua: 阶段是所有请求处理阶段中最为重要的一个,运行在这个阶段的配置指令一般都肩负着生成内容(content)并输出HTTP响应。 header_filter_by_lua: 一般只用于设置Cookie和Headers等 该阶段不能运行Output API、Control API、Subrequest API、Cosocket API body_filter_by_lua: 一般会在一次请求中被调用多次, 因为这是实现基于 HTTP 1.1 chunked 编码的所谓“流式输出”的。 该阶段不能运行Output API、Control API、Subrequest API、Cosocket API log_by_lua: 该阶段总是运行在请求结束的时候,用于请求的后续操作,如在共享内存中进行统计数据,如果要高精确的数据统计,应该使用body_filter_by_lua。 该阶段不能运行Output API、Control API、Subrequest API、Cosocket API timer:

2.2.2. Assignment operations

and break do else elseif end false for function if in local nil not or repeat return then true until while2.2.3. Logical operations 支持 +, -, *, /,^ 比如2^3 结果为8, 2^4结果为16。 连接两个字符串,用".."运处符, php为".", JAVA、C#为"+"a,b,c,d=1,2,3,4 -- 多变量一起赋值 a,b=b,a --交换变量功能 在默认情况下,变量总是认为是全局的。假如需要定义局部变量,则在第一次赋值的时候,需要用local说明。比如: local a,b,c = 1,2,3 -- a,b,c都是局部变量

2.3. Conditional judgment statement

2.3.1. if

and, or, not 在Lua中,只有false和nil才计算为false,其它任何数据都计算为true,0也是true and 和 or的运算结果不是true和false,而是和它的两个操作数相关。 a and b:如果a为false,则返回a;a true 返回b a or b:如果 a 为true,则返回a;a false 返回b

2.3.2. repeat

模拟C语言中的语句:x = a? b : c,在Lua中,可以写成:x = a and b or c。 最有用的语句是: x = x or v,它相当于:if not x then x = v end 。

2.3.3. while

if 条件 then ... elseif 条件 then ... else ... end

2.3.4. for

repeat ... until 条件while 条件 do ... end

2.4. Common structures

2.4.1 . table

for 变量=初值, 终点值, 步进 do ... end

;Example 1

for 变量1, 变量2, ... 变量n in 表或枚举函数 do ... end

;Example 2

1. table 是 lua 中最重要的数据类型。 2. table 类似于 python 中的字典。 3. table 只能通过构造式来创建

2.4.2. Lua table empty judgment

There is often such a requirement in the project script Lua

Lua代码 tab = { a = 10, b = 20, c = 30, d = 40 } print(tab["a"]) 注释: 1)table 中的每项要求是 key = value 的形式 2)key 只能是字符串, 这里的 a, b, c, d 都是字符串,但是不能加上引号 3)通过 key 来访问 table 的值,这时候, a 必须加上引号

2.5. Reference

tab = { 10, m = 20, 11, 12, 13 } print(tab[1]) = 10 print(tab[2]) = 11 print(tab[3]) = 12 print(tab[4]) = 13 获取表长度: print(table.getn(tab)) -> 4 print(#tab) -> 4 遍历表: for k, v in pairs(tab) do print(k, ":", v) end 1 : 10 2 : 11 3 : 12 4 : 13 m : 20 注释: 1)省略key,会自动以1开始编号,并跳过设置过的key 2)获取表长度,只有当表使用1自动编号开始,可以获取

The above has introduced the use and sharing of Ngx_Lua, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template