第四五章 (Nginx+Lua)Lua模块开发

在实际开发中,不可能把所有代码写到一个大而全的lua文件中,需要进行分模块开发;而且模块化是高性能Lua应用的关键。使用require第一次导入模块后,所有Nginx 进程全局共享模块的数据和代码,每个Worker进程需要时会得到此模块的一个副本(Copy-On-Write),即模块可以认为是每Worker进程共享而不是每Nginx Server共享;另外注意之前我们使用init_by_lua中初始化的全局变量是每请求复制一个;如果想在多个Worker进程间共享数据可以使用ngx.shared.DICT或如Redis之类的存储。

 

在/usr/example/lualib中已经提供了大量第三方开发库如cjson、redis客户端、mysql客户端:

cjson.so

resty/

   aes.lua

   core.lua

   dns/

   lock.lua

   lrucache/

   lrucache.lua

   md5.lua

   memcached.lua

   mysql.lua

   random.lua

   redis.lua

   ……

 

 

需要注意在使用前需要将库在nginx.conf中导入:

Java代码  
  1. #lua模块路径,其中”;;”表示默认搜索路径,默认到/usr/servers/nginx下找  
  2. lua_package_path "/usr/example/lualib/?.lua;;";  #lua 模块  
  3. lua_package_cpath "/usr/example/lualib/?.so;;";  #c模块   

使用方式是在lua中通过如下方式引入

Java代码  
  1. local cjson = require(“cjson”)  
  2. local redis = require(“resty.redis”)   

接下来我们来开发一个简单的lua模块。

Java代码  
  1. vim /usr/example/lualib/module1.lua  
Java代码  
  1. local count = 0  
  2. local function hello()  
  3.    count = count + 1  
  4.    ngx.say("count : ", count)  
  5. end  
  6.   
  7. local _M = {  
  8.    hello = hello  
  9. }  
  10.   
  11. return _M  

开发时将所有数据做成局部变量/局部函数;通过 _M导出要暴露的函数,实现模块化封装。

 

接下来创建test_module_1.lua

Java代码  
  1. vim /usr/example/lua/test_module_1.lua  
Java代码  
  1. local module1 = require("module1")  
  2.   
  3. module1.hello()  

 使用 local var = require("模块名"),该模块会到lua_package_path和lua_package_cpath声明的的位置查找我们的模块,对于多级目录的使用require("目录1.目录2.模块名")加载。

 

example.conf配置

Java代码  
  1. location /lua_module_1 {  
  2.     default_type 'text/html';  
  3.     lua_code_cache on;  
  4.     content_by_lua_file /usr/example/lua/test_module_1.lua;  
  5. }  

 

访问如http://192.168.1.2/lua_module_1进行测试,会得到类似如下的数据,count会递增

count : 1

count :2

……

count :N

 

此时可能发现count一直递增,假设我们的worker_processes  2,我们可以通过kill -9 nginx worker process杀死其中一个Worker进程得到count数据变化。

 

 

假设我们创建了vim /usr/example/lualib/test/module2.lua模块,可以通过local module2 = require("test.module2")加载模块

 

基本的模块开发就完成了,如果是只读数据可以通过模块中声明local变量存储;如果想在每Worker进程共享,请考虑竞争;如果要在多个Worker进程间共享请考虑使用ngx.shared.DICT或如Redis存储。

 

第五章 常用Lua开发库1-redis、mysql、http客户端

对于开发来说需要有好的生态开发库来辅助我们快速开发,而Lua中也有大多数我们需要的第三方开发库如Redis、Memcached、Mysql、Http客户端、JSON、模板引擎等。

一些常见的Lua库可以在github上搜索,https://github.com/search?utf8=%E2%9C%93&q=lua+resty

 

Redis客户端

lua-resty-redis是为基于cosocket API的ngx_lua提供的Lua redis客户端,通过它可以完成Redis的操作。默认安装OpenResty时已经自带了该模块,使用文档可参考https://github.com/openresty/lua-resty-redis

 

在测试之前请启动Redis实例:

nohup /usr/servers/redis-2.8.19/src/redis-server  /usr/servers/redis-2.8.19/redis_6660.conf &

 

1、基本操作

 

编辑test_redis_baisc.lua

Java代码  
  1. local function close_redis(red)  
  2.     if not red then  
  3.         return  
  4.     end  
  5.     local ok, err = red:close()  
  6.     if not ok then  
  7.         ngx.say("close redis error : ", err)  
  8.     end  
  9. end  
  10.   
  11. local redis = require("resty.redis")  
  12.   
  13. --创建实例  
  14. local red = redis:new()  
  15. --设置超时(毫秒)  
  16. red:set_timeout(1000)  
  17. --建立连接  
  18. local ip = "127.0.0.1"  
  19. local port = 6660  
  20. local ok, err = red:connect(ip, port)  
  21. if not ok then  
  22.     ngx.say("connect to redis error : ", err)  
  23.     return close_redis(red)  
  24. end  
  25. --调用API进行处理  
  26. ok, err = red:set("msg", "hello world")  
  27. if not ok then  
  28.     ngx.say("set msg error : ", err)  
  29.     return close_redis(red)  
  30. end  
  31.   
  32. --调用API获取数据  
  33. local resp, err = red:get("msg")  
  34. if not resp then  
  35.     ngx.say("get msg error : ", err)  
  36.     return close_redis(red)  
  37. end  
  38. --得到的数据为空处理  
  39. if resp == ngx.null then  
  40.     resp = ''  --比如默认值  
  41. end  
  42. ngx.say("msg : ", resp)  
  43.   
  44. close_redis(red)  

基本逻辑很简单,要注意此处判断是否为nil,需要跟ngx.null比较。

 

2、example.conf配置文件

Java代码  
  1.  location /lua_redis_basic {  
  2.     default_type 'text/html';  
  3.     lua_code_cache on;  
  4.     content_by_lua_file /usr/example/lua/test_redis_basic.lua;  
  5. }  

  

3、访问如http://192.168.1.2/lua_redis_basic进行测试,正常情况得到如下信息

msg : hello world

 

2、连接池

建立TCP连接需要三次握手而释放TCP连接需要四次握手,而这些往返时延仅需要一次,以后应该复用TCP连接,此时就可以考虑使用连接池,即连接池可以复用连接。

我们只需要将之前的close_redis函数改造为如下即可: 

Java代码  
  1. local function close_redis(red)  
  2.     if not red then  
  3.         return  
  4.     end  
  5.     --释放连接(连接池实现)  
  6.     local pool_max_idle_time = 10000 --毫秒  
  7.     local pool_size = 100 --连接池大小  
  8.     local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)  
  9.     if not ok then  
  10.         ngx.say("set keepalive error : ", err)  
  11.     end  
  12. end  

即设置空闲连接超时时间防止连接一直占用不释放;设置连接池大小来复用连接。

 

此处假设调用red:set_keepalive(),连接池大小通过nginx.conf中http部分的如下指令定义:

#默认连接池大小,默认30

lua_socket_pool_size 30;

#默认超时时间,默认60s

lua_socket_keepalive_timeout 60s;

 

注意:

1、连接池是每Worker进程的,而不是每Server的;

2、当连接超过最大连接池大小时,会按照LRU算法回收空闲连接为新连接使用;

3、连接池中的空闲连接出现异常时会自动被移除;

4、连接池是通过ip和port标识的,即相同的ip和port会使用同一个连接池(即使是不同类型的客户端如Redis、Memcached);

5、连接池第一次set_keepalive时连接池大小就确定下了,不会再变更;

5、cosocket的连接池http://wiki.nginx.org/HttpLuaModule#tcpsock:setkeepalive

 

3、pipeline

pipeline即管道,可以理解为把多个命令打包然后一起发送;MTU(Maxitum Transmission Unit 最大传输单元)为二层包大小,一般为1500字节;而MSS(Maximum Segment Size 最大报文分段大小)为四层包大小,其一般是1500-20(IP报头)-20(TCP报头)=1460字节;因此假设我们执行的多个Redis命令能在一个报文中传输的话,可以减少网络往返来提高速度。因此可以根据实际情况来选择走pipeline模式将多个命令打包到一个报文发送然后接受响应,而Redis协议也能很简单的识别和解决粘包。

 

1、修改之前的代码片段

Java代码  
  1. red:init_pipeline()  
  2. red:set("msg1", "hello1")  
  3. red:set("msg2", "hello2")  
  4. red:get("msg1")  
  5. red:get("msg2")  
  6. local respTable, err = red:commit_pipeline()  
  7.   
  8. --得到的数据为空处理  
  9. if respTable == ngx.null then  
  10.     respTable = {}  --比如默认值  
  11. end  
  12.   
  13. --结果是按照执行顺序返回的一个table  
  14. for i, v in ipairs(respTable) do  
  15.    ngx.say("msg : ", v, "<br/>")  
  16. end  

通过init_pipeline()初始化,然后通过commit_pipieline()打包提交init_pipeline()之后的Redis命令;返回结果是一个lua table,可以通过ipairs循环获取结果;

 

2、配置相应location,测试得到的结果

msg : OK
msg : OK
msg : hello1
msg : hello2

 

 

3、Redis Lua脚本

利用Redis单线程特性,可以通过在Redis中执行Lua脚本实现一些原子操作。如之前的red:get("msg")可以通过如下两种方式实现:

1、直接eval:

Java代码  
  1. local resp, err = red:eval("return redis.call('get', KEYS[1])", 1, "msg");   

2、script load然后evalsha  SHA1 校验和,这样可以节省脚本本身的服务器带宽:

Java代码  
  1. local sha1, err = red:script("load",  "return redis.call('get', KEYS[1])");  
  2. if not sha1 then  
  3.    ngx.say("load script error : ", err)  
  4.    return close_redis(red)  
  5. end  
  6. ngx.say("sha1 : ", sha1, "<br/>")  
  7. local resp, err = red:evalsha(sha1, 1, "msg");  

首先通过script load导入脚本并得到一个sha1校验和(仅需第一次导入即可),然后通过evalsha执行sha1校验和即可,这样如果脚本很长通过这种方式可以减少带宽的消耗。 

 

此处仅介绍了最简单的redis lua脚本,更复杂的请参考官方文档学习使用。

 

另外Redis集群分片算法该客户端没有提供需要自己实现,当然可以考虑直接使用类似于Twemproxy这种中间件实现。

Memcached客户端使用方式和本文类似,本文就不介绍了。

 

Mysql客户端

lua-resty-mysql是为基于cosocket API的ngx_lua提供的Lua Mysql客户端,通过它可以完成Mysql的操作。默认安装OpenResty时已经自带了该模块,使用文档可参考https://github.com/openresty/lua-resty-mysql

 

1、编辑test_mysql.lua

Java代码  
  1. local function close_db(db)  
  2.     if not db then  
  3.         return  
  4.     end  
  5.     db:close()  
  6. end  
  7.   
  8. local mysql = require("resty.mysql")  
  9. --创建实例  
  10. local db, err = mysql:new()  
  11. if not db then  
  12.     ngx.say("new mysql error : ", err)  
  13.     return  
  14. end  
  15. --设置超时时间(毫秒)  
  16. db:set_timeout(1000)  
  17.   
  18. local props = {  
  19.     host = "127.0.0.1",  
  20.     port = 3306,  
  21.     database = "mysql",  
  22.     user = "root",  
  23.     password = "123456"  
  24. }  
  25.   
  26. local res, err, errno, sqlstate = db:connect(props)  
  27.   
  28. if not res then  
  29.    ngx.say("connect to mysql error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  
  30.    return close_db(db)  
  31. end  
  32.   
  33. --删除表  
  34. local drop_table_sql = "drop table if exists test"  
  35. res, err, errno, sqlstate = db:query(drop_table_sql)  
  36. if not res then  
  37.    ngx.say("drop table error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  
  38.    return close_db(db)  
  39. end  
  40.   
  41. --创建表  
  42. local create_table_sql = "create table test(id int primary key auto_increment, ch varchar(100))"  
  43. res, err, errno, sqlstate = db:query(create_table_sql)  
  44. if not res then  
  45.    ngx.say("create table error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  
  46.    return close_db(db)  
  47. end  
  48.   
  49. --插入  
  50. local insert_sql = "insert into test (ch) values('hello')"  
  51. res, err, errno, sqlstate = db:query(insert_sql)  
  52. if not res then  
  53.    ngx.say("insert error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  
  54.    return close_db(db)  
  55. end  
  56.   
  57. res, err, errno, sqlstate = db:query(insert_sql)  
  58.   
  59. ngx.say("insert rows : ", res.affected_rows, " , id : ", res.insert_id, "<br/>")  
  60.   
  61. --更新  
  62. local update_sql = "update test set ch = 'hello2' where id =" .. res.insert_id  
  63. res, err, errno, sqlstate = db:query(update_sql)  
  64. if not res then  
  65.    ngx.say("update error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  
  66.    return close_db(db)  
  67. end  
  68.   
  69. ngx.say("update rows : ", res.affected_rows, "<br/>")  
  70. --查询  
  71. local select_sql = "select id, ch from test"  
  72. res, err, errno, sqlstate = db:query(select_sql)  
  73. if not res then  
  74.    ngx.say("select error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  
  75.    return close_db(db)  
  76. end  
  77.   
  78.   
  79. for i, row in ipairs(res) do  
  80.    for name, value in pairs(row) do  
  81.      ngx.say("select row ", i, " : ", name, " = ", value, "<br/>")  
  82.    end  
  83. end  
  84.   
  85. ngx.say("<br/>")  
  86. --防止sql注入  
  87. local ch_param = ngx.req.get_uri_args()["ch"] or ''  
  88. --使用ngx.quote_sql_str防止sql注入  
  89. local query_sql = "select id, ch from test where ch = " .. ngx.quote_sql_str(ch_param)  
  90. res, err, errno, sqlstate = db:query(query_sql)  
  91. if not res then  
  92.    ngx.say("select error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  
  93.    return close_db(db)  
  94. end  
  95.   
  96. for i, row in ipairs(res) do  
  97.    for name, value in pairs(row) do  
  98.      ngx.say("select row ", i, " : ", name, " = ", value, "<br/>")  
  99.    end  
  100. end  
  101.   
  102. --删除  
  103. local delete_sql = "delete from test"  
  104. res, err, errno, sqlstate = db:query(delete_sql)  
  105. if not res then  
  106.    ngx.say("delete error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  
  107.    return close_db(db)  
  108. end  
  109.   
  110. ngx.say("delete rows : ", res.affected_rows, "<br/>")  
  111.   
  112.   
  113. close_db(db)  

 

对于新增/修改/删除会返回如下格式的响应:

Java代码  
  1. {  
  2.     insert_id = 0,  
  3.     server_status = 2,  
  4.     warning_count = 1,  
  5.     affected_rows = 32,  
  6.     message = nil  
  7. }  

affected_rows表示操作影响的行数,insert_id是在使用自增序列时产生的id。

 

对于查询会返回如下格式的响应:

Java代码  
  1. {  
  2.     { id= 1, ch= "hello"},  
  3.     { id= 2, ch= "hello2"}  
  4. }  

null将返回ngx.null。

 

2、example.conf配置文件

Java代码  
  1. location /lua_mysql {  
  2.    default_type 'text/html';  
  3.    lua_code_cache on;  
  4.    content_by_lua_file /usr/example/lua/test_mysql.lua;  
  5. }  
 

3、访问如http://192.168.1.2/lua_mysql?ch=hello进行测试,得到如下结果

Java代码  
  1. insert rows : 1 , id : 2  
  2. update rows : 1  
  3. select row 1 : ch = hello  
  4. select row 1 : id = 1  
  5. select row 2 : ch = hello2  
  6. select row 2 : id = 2  
  7. select row 1 : ch = hello  
  8. select row 1 : id = 1  
  9. delete rows : 2  

客户端目前还没有提供预编译SQL支持(即占位符替换位置变量),这样在入参时记得使用ngx.quote_sql_str进行字符串转义,防止sql注入;连接池和之前Redis客户端完全一样就不介绍了。

 

对于Mysql客户端的介绍基本够用了,更多请参考https://github.com/openresty/lua-resty-mysql

 

其他如MongoDB等数据库的客户端可以从github上查找使用。

 

Http客户端

OpenResty默认没有提供Http客户端,需要使用第三方提供;当然我们可以通过ngx.location.capture 去方式实现,但是有一些限制,后边我们再做介绍。

 

我们可以从github上搜索相应的客户端,比如https://github.com/pintsized/lua-resty-http

 

lua-resty-http

 

1、下载lua-resty-http客户端到lualib 

Java代码  
  1. cd /usr/example/lualib/resty/  
  2. wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http_headers.lua  
  3. wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http.lua  
 

2、test_http_1.lua

Java代码  
  1. local http = require("resty.http")  
  2. --创建http客户端实例  
  3. local httpc = http.new()  
  4.   
  5. local resp, err = httpc:request_uri("http://s.taobao.com", {  
  6.     method = "GET",  
  7.     path = "/search?q=hello",  
  8.     headers = {  
  9.         ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36"  
  10.     }  
  11. })  
  12.   
  13. if not resp then  
  14.     ngx.say("request error :", err)  
  15.     return  
  16. end  
  17.   
  18. --获取状态码  
  19. ngx.status = resp.status  
  20.   
  21. --获取响应头  
  22. for k, v in pairs(resp.headers) do  
  23.     if k ~= "Transfer-Encoding" and k ~= "Connection" then  
  24.         ngx.header[k] = v  
  25.     end  
  26. end  
  27. --响应体  
  28. ngx.say(resp.body)  
  29.   
  30. httpc:close()  

 

响应头中的Transfer-Encoding和Connection可以忽略,因为这个数据是当前server输出的。

 

3、example.conf配置文件

Java代码  
  1. location /lua_http_1 {  
  2.    default_type 'text/html';  
  3.    lua_code_cache on;  
  4.    content_by_lua_file /usr/example/lua/test_http_1.lua;  
  5. }  
4、在nginx.conf中的http部分添加如下指令来做DNS解析
Java代码  
  1. resolver 8.8.8.8;  
记得要配置DNS解析器resolver 8.8.8.8,否则域名是无法解析的。
5、访问如http://192.168.1.2/lua_http_1会看到淘宝的搜索界面。

使用方式比较简单,如超时和连接池设置和之前Redis客户端一样,不再阐述。更多客户端使用规则请参考https://github.com/pintsized/lua-resty-http

 

ngx.location.capture

ngx.location.capture也可以用来完成http请求,但是它只能请求到相对于当前nginx服务器的路径,不能使用之前的绝对路径进行访问,但是我们可以配合nginx upstream实现我们想要的功能。

 

1、在nginx.cong中的http部分添加如下upstream配置

Java代码  
  1. upstream backend {  
  2.     server s.taobao.com;  
  3.     keepalive 100;  
  4. }  

即我们将请求upstream到backend;另外记得一定要添加之前的DNS解析器。

 

2、在example.conf配置如下location

Java代码  
  1. location ~ /proxy/(.*) {  
  2.    internal;  
  3.    proxy_pass http://backend/$1$is_args$args;  
  4. }  

internal表示只能内部访问,即外部无法通过url访问进来; 并通过proxy_pass将请求转发到upstream。

 

3、test_http_2.lua

Java代码  
  1. local resp = ngx.location.capture("/proxy/search", {  
  2.     method = ngx.HTTP_GET,  
  3.     args = {q = "hello"}  
  4.   
  5. })  
  6. if not resp then  
  7.     ngx.say("request error :", err)  
  8.     return  
  9. end  
  10. ngx.log(ngx.ERR, tostring(resp.status))  
  11.   
  12. --获取状态码  
  13. ngx.status = resp.status  
  14.   
  15. --获取响应头  
  16. for k, v in pairs(resp.header) do  
  17.     if k ~= "Transfer-Encoding" and k ~= "Connection" then  
  18.         ngx.header[k] = v  
  19.     end  
  20. end  
  21. --响应体  
  22. if resp.body then  
  23.     ngx.say(resp.body)  
  24. end  

通过ngx.location.capture发送一个子请求,此处因为是子请求,所有请求头继承自当前请求,还有如ngx.ctx和ngx.var是否继承可以参考官方文档http://wiki.nginx.org/HttpLuaModule#ngx.location.capture。 另外还提供了ngx.location.capture_multi用于并发发出多个请求,这样总的响应时间是最慢的一个,批量调用时有用。

 

4、example.conf配置文件

Java代码  
  1. location /lua_http_2 {  
  2.    default_type 'text/html';  
  3.    lua_code_cache on;  
  4.    content_by_lua_file /usr/example/lua/test_http_2.lua;  
  5. }  

 

5、访问如http://192.168.1.2/lua_http_2进行测试可以看到淘宝搜索界面。

 

我们通过upstream+ngx.location.capture方式虽然麻烦点,但是得到更好的性能和upstream的连接池、负载均衡、故障转移、proxy cache等特性。

 

JSON库

 

在进行数据传输时JSON格式目前应用广泛,因此从Lua对象与JSON字符串之间相互转换是一个非常常见的功能;目前Lua也有几个JSON库,本人用过cjson、dkjson。其中cjson的语法严格(比如unicode \u0020\u7eaf),要求符合规范否则会解析失败(如\u002),而dkjson相对宽松,当然也可以通过修改cjson的源码来完成一些特殊要求。而在使用dkjson时也没有遇到性能问题,目前使用的就是dkjson。使用时要特别注意的是大部分JSON库都仅支持UTF-8编码;因此如果你的字符编码是如GBK则需要先转换为UTF-8然后进行处理。

1.1、test_cjson.lua

Java代码  
  1. local cjson = require("cjson")  
  2.   
  3. --lua对象到字符串  
  4. local obj = {  
  5.     id = 1,  
  6.     name = "zhangsan",  
  7.     age = nil,  
  8.     is_male = false,  
  9.     hobby = {"film", "music", "read"}  
  10. }  
  11.   
  12. local str = cjson.encode(obj)  
  13. ngx.say(str, "<br/>")  
  14.   
  15. --字符串到lua对象  
  16. str = '{"hobby":["film","music","read"],"is_male":false,"name":"zhangsan","id":1,"age":null}'  
  17. local obj = cjson.decode(str)  
  18.   
  19. ngx.say(obj.age, "<br/>")  
  20. ngx.say(obj.age == nil, "<br/>")  
  21. ngx.say(obj.age == cjson.null, "<br/>")  
  22. ngx.say(obj.hobby[1], "<br/>")  
  23.   
  24.   
  25. --循环引用  
  26. obj = {  
  27.    id = 1  
  28. }  
  29. obj.obj = obj  
  30. -- Cannot serialise, excessive nesting  
  31. --ngx.say(cjson.encode(obj), "<br/>")  
  32. local cjson_safe = require("cjson.safe")  
  33. --nil  
  34. ngx.say(cjson_safe.encode(obj), "<br/>")  
null将会转换为cjson.null;循环引用会抛出异常Cannot serialise, excessive nesting,默认解析嵌套深度是1000,可以通过cjson.encode_max_depth()设置深度提高性能;使用cjson.safe不会抛出异常而是返回nil。 

 

1.2、example.conf配置文件

Java代码  
  1. location ~ /lua_cjson {  
  2.    default_type 'text/html';  
  3.    lua_code_cache on;  
  4.    content_by_lua_file /usr/example/lua/test_cjson.lua;  
  5. }  
 

1.3、访问如http://192.168.1.2/lua_cjson将得到如下结果

Java代码  
  1. {"hobby":["film","music","read"],"is_male":false,"name":"zhangsan","id":1}  
  2. null  
  3. false  
  4. true  
  5. film  
  6. nil  

 

lua-cjson文档http://www.kyne.com.au/~mark/software/lua-cjson-manual.html

 

接下来学习下dkjson。

 

2.1、下载dkjson库 

Java代码  
  1. cd /usr/example/lualib/  
  2. wget http://dkolf.de/src/dkjson-lua.fsl/raw/dkjson.lua?name=16cbc26080996d9da827df42cb0844a25518eeb3 -O dkjson.lua  

 

2.2、test_dkjson.lua

Java代码  
  1. local dkjson = require("dkjson")  
  2.   
  3. --lua对象到字符串  
  4. local obj = {  
  5.     id = 1,  
  6.     name = "zhangsan",  
  7.     age = nil,  
  8.     is_male = false,  
  9.     hobby = {"film", "music", "read"}  
  10. }  
  11.   
  12. local str = dkjson.encode(obj, {indent = true})  
  13. ngx.say(str, "<br/>")  
  14.   
  15. --字符串到lua对象  
  16. str = '{"hobby":["film","music","read"],"is_male":false,"name":"zhangsan","id":1,"age":null}'  
  17. local obj, pos, err = dkjson.decode(str, 1, nil)  
  18.   
  19. ngx.say(obj.age, "<br/>")  
  20. ngx.say(obj.age == nil, "<br/>")  
  21. ngx.say(obj.hobby[1], "<br/>")  
  22.   
  23. --循环引用  
  24. obj = {  
  25.    id = 1  
  26. }  
  27. obj.obj = obj  
  28. --reference cycle  
  29. --ngx.say(dkjson.encode(obj), "<br/>")                                       
默认情况下解析的json的字符会有缩排和换行,使用{indent = true}配置将把所有内容放在一行。和cjson不同的是解析json字符串中的null时会得到nil。  

2.3、example.conf配置文件

Java代码  
  1. location ~ /lua_dkjson {  
  2.    default_type 'text/html';  
  3.    lua_code_cache on;  
  4.    content_by_lua_file /usr/example/lua/test_dkjson.lua;  
  5. }  
 

2.4、访问如http://192.168.1.2/lua_dkjson将得到如下结果

Java代码  
  1. { "hobby":["film","music","read"], "is_male":false, "name":"zhangsan", "id":1 }  
  2. nil  
  3. true  
  4. film  

dkjson文档http://dkolf.de/src/dkjson-lua.fsl/homehttp://dkolf.de/src/dkjson-lua.fsl/wiki?name=Documentation

 

编码转换

我们在使用一些类库时会发现大部分库仅支持UTF-8编码,因此如果使用其他编码的话就需要进行编码转换的处理;而Linux上最常见的就是iconv,而lua-iconv就是它的一个Lua API的封装。

 

安装lua-iconv可以通过如下两种方式:

ubuntu下可以使用如下方式

Java代码  
  1. apt-get install luarocks  
  2. luarocks install lua-iconv   
  3. cp /usr/local/lib/lua/5.1/iconv.so  /usr/example/lualib/  

源码安装方式,需要有gcc环境

Java代码  
  1. wget https://github.com/do^Cloads/ittner/lua-iconv/lua-iconv-7.tar.gz  
  2. tar -xvf lua-iconv-7.tar.gz  
  3. cd lua-iconv-7  
  4. gcc -O2 -fPIC -I/usr/include/lua5.1 -c luaiconv.c -o luaiconv.o -I/usr/include  
  5. gcc -shared -o iconv.so -L/usr/local/lib luaiconv.o -L/usr/lib  
  6. cp iconv.so  /usr/example/lualib/  

  

1、test_iconv.lua

Java代码  
  1. ngx.say("中文")  

此时文件编码必须为UTF-8,即Lua文件编码为什么里边的字符编码就是什么。

  

2、example.conf配置文件

Java代码  
  1. location ~ /lua_iconv {  
  2.    default_type 'text/html';  
  3.    charset gbk;  
  4.    lua_code_cache on;  
  5.    content_by_lua_file /usr/example/lua/test_iconv.lua;  
  6. }  

通过charset告诉浏览器我们的字符编码为gbk。  

 

3、访问 http://192.168.1.2/lua_iconv会发现输出乱码;

 

此时需要我们将test_iconv.lua中的字符进行转码处理:

Java代码  
  1. local iconv = require("iconv")  
  2. local togbk = iconv.new("gbk", "utf-8")  
  3. local str, err = togbk:iconv("中文")  
  4. ngx.say(str)  

通过转码我们得到最终输出的内容编码为gbk, 使用方式iconv.new(目标编码, 源编码)。

 

有如下可能出现的错误:

Java代码  
  1. nil     
  2.     没有错误成功。  
  3. iconv.ERROR_NO_MEMORY  
  4.     内存不足。  
  5. iconv.ERROR_INVALID  
  6.     有非法字符。  
  7. iconv.ERROR_INCOMPLETE  
  8.     有不完整字符。  
  9. iconv.ERROR_FINALIZED  
  10.     使用已经销毁的转换器,比如垃圾回收了。  
  11. iconv.ERROR_UNKNOWN   
  12.     未知错误  

 

iconv在转换时遇到非法字符或不能转换的字符就会失败,此时可以使用如下方式忽略转换失败的字符

Java代码  
  1. local togbk_ignore = iconv.new("GBK//IGNORE", "UTF-8")  

 

另外在实际使用中进行UTF-8到GBK转换过程时,会发现有些字符在GBK编码表但是转换不了,此时可以使用更高的编码GB18030来完成转换。 

 

更多介绍请参考http://ittner.github.io/lua-iconv/

 

位运算

Lua 5.3之前是没有提供位运算支持的,需要使用第三方库,比如LuaJIT提供了bit库。

1、test_bit.lua 

Java代码  
  1. local bit = require("bit")  
  2. ngx.say(bit.lshift(1, 2))  
lshift进行左移位运算,即得到4。

  

其他位操作API请参考http://bitop.luajit.org/api.html。Lua 5.3的位运算操作符http://cloudwu.github.io/lua53doc/manual.html#3.4.2

 

cache

ngx_lua模块本身提供了全局共享内存ngx.shared.DICT可以实现全局共享,另外可以使用如Redis来实现缓存。另外还一个lua-resty-lrucache实现,其和ngx.shared.DICT不一样的是它是每Worker进程共享,即每个Worker进行会有一份缓存,而且经过实际使用发现其性能不如ngx.shared.DICT。但是其好处就是不需要进行全局配置。

 

1、创建缓存模块来实现只初始化一次:

Java代码  
  1. vim /usr/example/lualib/mycache.lua   
Java代码  
  1. local lrucache = require("resty.lrucache")  
  2. --创建缓存实例,并指定最多缓存多少条目  
  3. local cache, err = lrucache.new(200)  
  4. if not cache then  
  5.    ngx.log(ngx.ERR, "create cache error : ", err)  
  6. end  
  7.   
  8. local function set(key, value, ttlInSeconds)  
  9.     cache:set(key, value, ttlInSeconds)  
  10. end  
  11.   
  12. local function get(key)  
  13.     return cache:get(key)  
  14. end  
  15.   
  16. local _M = {  
  17.   set = set,  
  18.   get = get  
  19. }  
  20.   
  21. return _M  

此处利用了模块的特性实现了每个Worker进行只初始化一次cache实例。

 

2、test_lrucache.lua  

Java代码  
  1. local mycache = require("mycache")  
  2. local count = mycache.get("count") or 0  
  3. count = count + 1  
  4. mycache.set("count", count, 10 * 60 * 60) --10分钟  
  5. ngx.say(mycache.get("count"))                

可以实现诸如访问量统计,但仅是每Worker进程的。   

 

3、example.conf配置文件

Java代码  
  1. location ~ /lua_lrucache {  
  2.    default_type 'text/html';  
  3.    lua_code_cache on;  
  4.    content_by_lua_file /usr/example/lua/test_lrucache.lua;  
  5. }  

访问如http://192.168.1.2/lua_lrucache测试。

 

更多介绍请参考https://github.com/openresty/lua-resty-lrucache

 

字符串处理

Lua 5.3之前没有提供字符操作相关的函数,如字符串截取、替换等都是字节为单位操作;在实际使用时尤其包含中文的场景下显然不能满足需求;即使Lua 5.3也仅提供了基本的UTF-8操作

 

Lua UTF-8库

https://github.com/starwing/luautf8

 

LuaRocks安装

Java代码  
  1. #首先确保git安装了  
  2. apt-get install git  
  3. luarocks install utf8  
  4. cp /usr/local/lib/lua/5.1/utf8.so  /usr/example/lualib/  

 

源码安装

Java代码  
  1. wget https://github.com/starwing/luautf8/archive/master.zip  
  2. unzip master.zip  
  3. cd luautf8-master/  
  4. gcc -O2 -fPIC -I/usr/include/lua5.1 -c utf8.c -o utf8.o -I/usr/include  
  5. gcc -shared -o utf8.so -L/usr/local/lib utf8.o -L/usr/lib  

 

1、test_utf8.lua

Java代码  
  1. local utf8 = require("utf8")  
  2. local str = "abc中文"  
  3. ngx.say("len : ", utf8.len(str), "<br/>")  
  4. ngx.say("sub : ", utf8.sub(str, 1, 4))  
文件编码必须为UTF8,此处我们实现了最常用的字符串长度计算和字符串截取。
2、example.conf配置文件
Java代码  
  1. location ~ /lua_utf8 {  
  2.    default_type 'text/html';  
  3.    lua_code_cache on;  
  4.    content_by_lua_file /usr/example/lua/test_utf8.lua;  
  5. }  
  

3、访问如http://192.168.1.2/lua_utf8测试得到如下结果

len : 5
sub : abc中

 

字符串转换为unicode编码:

Java代码  
  1. local bit = require("bit")  
  2. local bit_band = bit.band  
  3. local bit_bor = bit.bor  
  4. local bit_lshift = bit.lshift  
  5. local string_format = string.format  
  6. local string_byte = string.byte  
  7. local table_concat = table.concat  
  8.   
  9. local function utf8_to_unicode(str)  
  10.     if not str or str == "" or str == ngx.null then  
  11.         return nil  
  12.     end  
  13.     local res, seq, val = {}, 0, nil  
  14.     for i = 1, #str do  
  15.         local c = string_byte(str, i)  
  16.         if seq == 0 then  
  17.             if val then  
  18.                 res[#res + 1] = string_format("%04x", val)  
  19.             end  
  20.   
  21.            seq = c < 0x80 and 1 or c < 0xE0 and 2 or c < 0xF0 and 3 or  
  22.                               c < 0xF8 and 4 or --c < 0xFC and 5 or c < 0xFE and 6 or  
  23.                               0  
  24.             if seq == 0 then  
  25.                 ngx.log(ngx.ERR, 'invalid UTF-8 character sequence' .. ",,," .. tostring(str))  
  26.                 return str  
  27.             end  
  28.   
  29.             val = bit_band(c, 2 ^ (8 - seq) - 1)  
  30.         else  
  31.             val = bit_bor(bit_lshift(val, 6), bit_band(c, 0x3F))  
  32.         end  
  33.         seq = seq - 1  
  34.     end  
  35.     if val then  
  36.         res[#res + 1] = string_format("%04x", val)  
  37.     end  
  38.     if #res == 0 then  
  39.         return str  
  40.     end  
  41.     return "\\u" .. table_concat(res, "\\u")  
  42. end  
  43.   
  44. ngx.say("utf8 to unicode : ", utf8_to_unicode("abc中文"), "<br/>")  

如上方法将输出utf8 to unicode : \u0061\u0062\u0063\u4e2d\u6587。

 

删除空格:

Java代码  
  1. local function ltrim(s)  
  2.     if not s then  
  3.         return s  
  4.     end  
  5.     local res = s  
  6.     local tmp = string_find(res, '%S')  
  7.     if not tmp then  
  8.         res = ''  
  9.     elseif tmp ~= 1 then  
  10.         res = string_sub(res, tmp)  
  11.     end  
  12.     return res  
  13. end  
  14.   
  15. local function rtrim(s)  
  16.     if not s then  
  17.         return s  
  18.     end  
  19.     local res = s  
  20.     local tmp = string_find(res, '%S%s*$')  
  21.     if not tmp then  
  22.         res = ''  
  23.     elseif tmp ~= #res then  
  24.         res = string_sub(res, 1, tmp)  
  25.     end  
  26.   
  27.     return res  
  28. end  
  29.   
  30. local function trim(s)  
  31.     if not s then  
  32.         return s  
  33.     end  
  34.     local res1 = ltrim(s)  
  35.     local res2 = rtrim(res1)  
  36.     return res2  
  37. end  

 

字符串分割:

Java代码  
  1. function split(szFullString, szSeparator)  
  2.     local nFindStartIndex = 1  
  3.     local nSplitIndex = 1  
  4.     local nSplitArray = {}  
  5.     while true do  
  6.        local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex)  
  7.        if not nFindLastIndex then  
  8.         nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString))  
  9.         break  
  10.        end  
  11.        nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1)  
  12.        nFindStartIndex = nFindLastIndex + string.len(szSeparator)  
  13.        nSplitIndex = nSplitIndex + 1  
  14.     end  
  15.     return nSplitArray  
  16. end  

如split("a,b,c", ",") 将得到一个分割后的table。

 

动态web网页开发是Web开发中一个常见的场景,比如像京东商品详情页,其页面逻辑是非常复杂的,需要使用模板技术来实现。而Lua中也有许多模板引擎,如目前我在使用的lua-resty-template,可以渲染很复杂的页面,借助LuaJIT其性能也是可以接受的。

 

如果学习过JavaEE中的servlet和JSP的话,应该知道JSP模板最终会被翻译成Servlet来执行;而lua-resty-template模板引擎可以认为是JSP,其最终会被翻译成Lua代码,然后通过ngx.print输出。

 

而lua-resty-template和大多数模板引擎是类似的,大体内容有:

模板位置:从哪里查找模板;

变量输出/转义:变量值输出;

代码片段:执行代码片段,完成如if/else、for等复杂逻辑,调用对象函数/方法;

注释:解释代码片段含义;

include:包含另一个模板片段;

其他:lua-resty-template还提供了不需要解析片段、简单布局、可复用的代码块、宏指令等支持。

 

首先需要下载lua-resty-template

Java代码  收藏代码
  1. cd /usr/example/lualib/resty/  
  2. wget https://raw.githubusercontent.com/bungle/lua-resty-template/master/lib/resty/template.lua  
  3. mkdir /usr/example/lualib/resty/html  
  4. cd /usr/example/lualib/resty/html   
  5. wget https://raw.githubusercontent.com/bungle/lua-resty-template/master/lib/resty/template/html.lua  

接下来就可以通过如下代码片段引用了

Java代码  收藏代码
  1. local template = require("resty.template")  

  

模板位置

我们需要告诉lua-resty-template去哪儿加载我们的模块,此处可以通过set指令定义template_location、template_root或者从root指令定义的位置加载。

 

如我们可以在example.conf配置文件的server部分定义

Java代码  收藏代码
  1. #first match ngx location  
  2. set $template_location "/templates";  
  3. #then match root read file  
  4. set $template_root "/usr/example/templates";  

也可以通过在server部分定义root指令

Java代码  收藏代码
  1. root /usr/example/templates;  

 

其顺序是

Java代码  收藏代码
  1. local function load_ngx(path)  
  2.     local file, location = path, ngx_var.template_location  
  3.     if file:sub(1)  == "/" then file = file:sub(2) end  
  4.     if location and location ~= "" then  
  5.         if location:sub(-1) == "/" then location = location:sub(1, -2) end  
  6.         local res = ngx_capture(location .. '/' .. file)  
  7.         if res.status == 200 then return res.body end  
  8.     end  
  9.     local root = ngx_var.template_root or ngx_var.document_root  
  10.     if root:sub(-1) == "/" then root = root:sub(1, -2) end  
  11.     return read_file(root .. "/" .. file) or path  
  12. end  

1、通过ngx.location.capture从template_location查找,如果找到(状态为为200)则使用该内容作为模板;此种方式是一种动态获取模板方式;

 

2、如果定义了template_root,则从该位置通过读取文件的方式加载模板;

3、如果没有定义template_root,则默认从root指令定义的document_root处加载模板。

 

此处建议首先template_root,如果实在有问题再使用template_location,尽量不要通过root指令定义的document_root加载,因为其本身的含义不是给本模板引擎使用的。

 

接下来定义模板位置

Java代码  收藏代码
  1. mkdir /usr/example/templates  
  2. mkdir /usr/example/templates2  

 

example.conf配置server部分

Java代码  收藏代码
  1. #first match ngx location  
  2. set $template_location "/templates";  
  3. #then match root read file  
  4. set $template_root "/usr/example/templates";  
  5.   
  6. location /templates {  
  7.      internal;  
  8.      alias /usr/example/templates2;  
  9. }  

首先查找/usr/example/template2,找不到会查找/usr/example/templates。

 

然后创建两个模板文件

Java代码  收藏代码
  1. vim /usr/example/templates2/t1.html  

内容为 

Java代码  收藏代码
  1. template2  

 

Java代码  收藏代码
  1. vim /usr/example/templates/t1.html  

内容为 

Java代码  收藏代码
  1. template1  

 

test_temlate_1.lua 

Java代码  收藏代码
  1. local template = require("resty.template")  
  2. template.render("t1.html")  

 

example.conf配置文件

Java代码  收藏代码
  1. location /lua_template_1 {  
  2.     default_type 'text/html';  
  3.     lua_code_cache on;  
  4.     content_by_lua_file /usr/example/lua/test_template_1.lua;  
  5. }  

访问如http://192.168.1.2/lua_template_1将看到template2输出。然后rm /usr/example/templates2/t1.html,reload nginx将看到template1输出。

 

接下来的测试我们会把模板文件都放到/usr/example/templates下。

 

API

使用模板引擎目的就是输出响应内容;主要用法两种:直接通过ngx.print输出或者得到模板渲染之后的内容按照想要的规则输出。

 

1、test_template_2.lua

Java代码  收藏代码
  1. local template = require("resty.template")  
  2. --是否缓存解析后的模板,默认true  
  3. template.caching(true)  
  4. --渲染模板需要的上下文(数据)  
  5. local context = {title = "title"}  
  6. --渲染模板  
  7. template.render("t1.html", context)  
  8.   
  9.   
  10. ngx.say("<br/>")  
  11. --编译得到一个lua函数  
  12. local func = template.compile("t1.html")  
  13. --执行函数,得到渲染之后的内容  
  14. local content = func(context)  
  15. --通过ngx API输出  
  16. ngx.say(content)  

常见用法即如下两种方式:要么直接将模板内容直接作为响应输出,要么得到渲染后的内容然后按照想要的规则输出。

 

2、examle.conf配置文件

Java代码  收藏代码
  1. location /lua_template_2 {  
  2.     default_type 'text/html';  
  3.     lua_code_cache on;  
  4.     content_by_lua_file /usr/example/lua/test_template_2.lua;  
  5. }  

  

使用示例

1、test_template_3.lua

Java代码  收藏代码
  1. local template = require("resty.template")  
  2.   
  3. local context = {  
  4.     title = "测试",  
  5.     name = "张三",  
  6.     description = "<script>alert(1);</script>",  
  7.     age = 20,  
  8.     hobby = {"电影", "音乐", "阅读"},  
  9.     score = {语文 = 90, 数学 = 80, 英语 = 70},  
  10.     score2 = {  
  11.         {name = "语文", score = 90},  
  12.         {name = "数学", score = 80},  
  13.         {name = "英语", score = 70},  
  14.     }  
  15. }  
  16.   
  17. template.render("t3.html", context)  

请确认文件编码为UTF-8;context即我们渲染模板使用的数据。 

 

2、模板文件/usr/example/templates/t3.html

Java代码  收藏代码
  1. {(header.html)}  
  2.    <body>  
  3.       {# 不转义变量输出 #}  
  4.       姓名:{* string.upper(name) *}<br/>  
  5.       {# 转义变量输出 #}  
  6.       简介:{{description}}<br/>  
  7.       {# 可以做一些运算 #}  
  8.       年龄: {* age + 1 *}<br/>  
  9.       {# 循环输出 #}  
  10.       爱好:  
  11.       {% for i, v in ipairs(hobby) do %}  
  12.          {% if i > 1 then %},{% end %}  
  13.          {* v *}  
  14.       {% end %}<br/>  
  15.   
  16.       成绩:  
  17.       {% local i = 1; %}  
  18.       {% for k, v in pairs(score) do %}  
  19.          {% if i > 1 then %},{% end %}  
  20.          {* k *} = {* v *}  
  21.          {% i = i + 1 %}  
  22.       {% end %}<br/>  
  23.       成绩2:  
  24.       {% for i = 1, #score2 do local t = score2[i] %}  
  25.          {% if i > 1 then %},{% end %}  
  26.           {* t.name *} = {* t.score *}  
  27.       {% end %}<br/>  
  28.       {# 中间内容不解析 #}  
  29.       {-raw-}{(file)}{-raw-}  
  30. {(footer.html)}  

{(include_file)}:包含另一个模板文件;

 

{* var *}:变量输出;

{{ var }}:变量转义输出;

{% code %}:代码片段;

{# comment #}:注释;

{-raw-}:中间的内容不会解析,作为纯文本输出;

 

模板最终被转换为Lua代码进行执行,所以模板中可以执行任意Lua代码。 

 

3、example.conf配置文件

Java代码  收藏代码
  1. location /lua_template_3 {  
  2.     default_type 'text/html';  
  3.     lua_code_cache on;  
  4.     content_by_lua_file /usr/example/lua/test_template_3.lua;  
  5. }  

访问如http://192.168.1.2/lua_template_3进行测试。 

posted @ 2022-02-16 14:50  hanease  阅读(240)  评论(0编辑  收藏  举报