在实际开发中,不可能把所有代码写到一个大而全的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中导入:

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

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

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

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

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

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

接下来创建test_module_1.lua

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

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

example.conf配置

  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

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

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

2、example.conf配置文件

  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函数改造为如下即可:

  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、修改之前的代码片段

  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. if respTable == ngx.null then
  9. respTable = {}  --比如默认值
  10. end
  11. --结果是按照执行顺序返回的一个table
  12. for i, v in ipairs(respTable) do
  13. ngx.say("msg : ", v, "<br/>")
  14. 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:

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

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

  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

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

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

  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。

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

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

null将返回ngx.null。

2、example.conf配置文件

  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进行测试,得到如下结果

  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

  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

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

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

3、example.conf配置文件

  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解析
  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配置

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

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

2、在example.conf配置如下location

  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

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

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

4、example.conf配置文件

  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

  1. local cjson = require("cjson")
  2. --lua对象到字符串
  3. local obj = {
  4. id = 1,
  5. name = "zhangsan",
  6. age = nil,
  7. is_male = false,
  8. hobby = {"film", "music", "read"}
  9. }
  10. local str = cjson.encode(obj)
  11. ngx.say(str, "<br/>")
  12. --字符串到lua对象
  13. str = '{"hobby":["film","music","read"],"is_male":false,"name":"zhangsan","id":1,"age":null}'
  14. local obj = cjson.decode(str)
  15. ngx.say(obj.age, "<br/>")
  16. ngx.say(obj.age == nil, "<br/>")
  17. ngx.say(obj.age == cjson.null, "<br/>")
  18. ngx.say(obj.hobby[1], "<br/>")
  19. --循环引用
  20. obj = {
  21. id = 1
  22. }
  23. obj.obj = obj
  24. -- Cannot serialise, excessive nesting
  25. --ngx.say(cjson.encode(obj), "<br/>")
  26. local cjson_safe = require("cjson.safe")
  27. --nil
  28. 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配置文件

  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将得到如下结果

  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库

  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

  1. local dkjson = require("dkjson")
  2. --lua对象到字符串
  3. local obj = {
  4. id = 1,
  5. name = "zhangsan",
  6. age = nil,
  7. is_male = false,
  8. hobby = {"film", "music", "read"}
  9. }
  10. local str = dkjson.encode(obj, {indent = true})
  11. ngx.say(str, "<br/>")
  12. --字符串到lua对象
  13. str = '{"hobby":["film","music","read"],"is_male":false,"name":"zhangsan","id":1,"age":null}'
  14. local obj, pos, err = dkjson.decode(str, 1, nil)
  15. ngx.say(obj.age, "<br/>")
  16. ngx.say(obj.age == nil, "<br/>")
  17. ngx.say(obj.hobby[1], "<br/>")
  18. --循环引用
  19. obj = {
  20. id = 1
  21. }
  22. obj.obj = obj
  23. --reference cycle
  24. --ngx.say(dkjson.encode(obj), "<br/>")

默认情况下解析的json的字符会有缩排和换行,使用{indent = true}配置将把所有内容放在一行。和cjson不同的是解析json字符串中的null时会得到nil。

2.3、example.conf配置文件

  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将得到如下结果

  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下可以使用如下方式

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

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

  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

  1. ngx.say("中文")

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

2、example.conf配置文件

  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中的字符进行转码处理:

  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(目标编码, 源编码)。

有如下可能出现的错误:

  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在转换时遇到非法字符或不能转换的字符就会失败,此时可以使用如下方式忽略转换失败的字符

  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

  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、创建缓存模块来实现只初始化一次:

  1. vim /usr/example/lualib/mycache.lua
  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. local function set(key, value, ttlInSeconds)
  8. cache:set(key, value, ttlInSeconds)
  9. end
  10. local function get(key)
  11. return cache:get(key)
  12. end
  13. local _M = {
  14. set = set,
  15. get = get
  16. }
  17. return _M

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

2、test_lrucache.lua

  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配置文件

  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安装

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

源码安装

  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

  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配置文件
  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编码:

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

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

删除空格:

  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. local function rtrim(s)
  15. if not s then
  16. return s
  17. end
  18. local res = s
  19. local tmp = string_find(res, '%S%s*$')
  20. if not tmp then
  21. res = ''
  22. elseif tmp ~= #res then
  23. res = string_sub(res, 1, tmp)
  24. end
  25. return res
  26. end
  27. local function trim(s)
  28. if not s then
  29. return s
  30. end
  31. local res1 = ltrim(s)
  32. local res2 = rtrim(res1)
  33. return res2
  34. end

字符串分割:

  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

  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

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

  1. local template = require("resty.template")

模板位置

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

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

  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指令

  1. root /usr/example/templates;

其顺序是

  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加载,因为其本身的含义不是给本模板引擎使用的。

接下来定义模板位置

  1. mkdir /usr/example/templates
  2. mkdir /usr/example/templates2

example.conf配置server部分

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

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

然后创建两个模板文件

  1. vim /usr/example/templates2/t1.html

内容为

  1. template2
  1. vim /usr/example/templates/t1.html

内容为

  1. template1

test_temlate_1.lua

  1. local template = require("resty.template")
  2. template.render("t1.html")

example.conf配置文件

  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

  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. ngx.say("<br/>")
  9. --编译得到一个lua函数
  10. local func = template.compile("t1.html")
  11. --执行函数,得到渲染之后的内容
  12. local content = func(context)
  13. --通过ngx API输出
  14. ngx.say(content)

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

2、examle.conf配置文件

  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

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

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

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

  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. {% local i = 1; %}
  17. {% for k, v in pairs(score) do %}
  18. {% if i > 1 then %},{% end %}
  19. {* k *} = {* v *}
  20. {% i = i + 1 %}
  21. {% end %}<br/>
  22. 成绩2:
  23. {% for i = 1, #score2 do local t = score2[i] %}
  24. {% if i > 1 then %},{% end %}
  25. {* t.name *} = {* t.score *}
  26. {% end %}<br/>
  27. {# 中间内容不解析 #}
  28. {-raw-}{(file)}{-raw-}
  29. {(footer.html)}

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

{* var *}:变量输出;

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

{% code %}:代码片段;

{# comment #}:注释;

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

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

3、example.conf配置文件

  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进行测试。

第四五章 (Nginx+Lua)Lua模块开发的更多相关文章

  1. 阶段一-01.万丈高楼,地基首要-第3章 用户登录注册模块开发-3-8 优化Swagger2显示

    左侧的全是英文 忽略api 把HelloController也忽略掉 重启api的服务,刷新页面.只剩下了passport的Controller 给passport接口加上注解. 重启服务,并刷新页面 ...

  2. 解剖Nginx·模块开发篇(1)跑起你的 Hello World 模块!

    1 学习 Nginx 模块开发需要有哪些准备? 需要的预备知识不多,有如下几点: 有过一些 C 语言的编程经历: 知道 Nginx 是干嘛的,并有过编写或改写 Nginx 的配置文件的经历. OK,就 ...

  3. 高并发 Nginx+Lua OpenResty系列(4)——Lua 模块开发

    在实际开发中,不可能把所有代码写到一个大而全的lua文件中,需要进行分模块开发:而且模块化是高性能Lua应用的关键.使用require第一次导入模块后,所有Nginx 进程全局共享模块的数据和代码,每 ...

  4. nginx 与 lua 开发环境搭建

    首先下载最新版的 相关软件 的安装文件. nginx: http://nginx.org/en/download.html LuaJIT: http://luajit.org/download.htm ...

  5. nginx 与 lua 开发笔记

    Nginx入门 本文目的是学习Nginx+Lua开发,对于Nginx基本知识可以参考如下文章: nginx启动.关闭.重启 http://www.cnblogs.com/derekchen/archi ...

  6. Nginx与Lua的开发

    1. Lua基础语法 安装lua hello world 也可以编写lua脚本 运行脚本 lua注释 变量 局部变量的话前面加个local 循环 if语句 2. Nginx与Lua开发环境 https ...

  7. nginx 安装 lua_nginx_module 模块(nginx——lua 学习笔记1)

    插入两个网站: nginx + lua 的OpenResty 开发 跟我学OpenResty(Nginx+Lua)开发目录贴 两个都是 可以根据目录一步步学习的. 1. 版本下载 nginx版本为 n ...

  8. Nginx使用Lua模块实现WAF

    前言:最近一段时间在写加密数据功能,对安全相关知识还是缺少积累,无意间接触到了WAF相关知识,刚好Nginx可以实现WAF功能,也简单学习了Lua这门语言,分享下 一.WAF产生的背景 过去企业通常会 ...

  9. Nginx Lua拓展模块操作Redis、Mysql

    # Nginx的拓展模块 # ngx_lua模块 # 淘宝开发的ngx_lua模块通过lua解释器集成近Nginx,可以采用lua脚本实现业务逻辑,由于lua的紧凑.快速以及内建协程,所以在保证宝兵法 ...

  10. nginx安装lua模块实现高并发

    nginx安装lua扩展模块 1.下载安装LuaJIT-2.0.4.tar.gz wget -c http://luajit.org/download/LuaJIT-2.0.4.tar.gz tar ...

随机推荐

  1. 计算机网络常见面试题(一):TCP/IP五层模型、TCP三次握手、四次挥手,TCP传输可靠性保障、ARQ协议

    文章目录 一.TCP/IP五层模型(重要) 二.应用层常见的协议 三.TCP与UDP 3.1 TCP.UDP的区别(重要) 3.2 运行于TCP.UDP上的协议 3.3 TCP的三次握手.四次挥手 3 ...

  2. 使用NTP,该如何同步时间?一文详解!

    ​ 一.NTP通信概述 很多场景中,由于业务需要,模块需要保持正确的系统时钟,才能正常工作.但是模块上电后的初试时间戳是946713600(即2000/01/01,16:00:00),所以同步时钟成为 ...

  3. cornerstone中raft_server_req_handlers源码解析

    1.概述 之前说过raft_server是cornerstone的核心,其中充满了很多req的发送,那么follower收到leader的req会怎么处理呢? 本文就是来解析cornerstone中处 ...

  4. 2019 ICPC Universidad Nacional de Colombia Programming Contest

    A. Amazon 给定\(n\)条直线(存在共线的情况),在每两条垂直的直线的交点处需要建一个交叉点,求交叉点的数量,注意需要去除共线时候的交叉点 题解 因为要除去共线的情况,我们考虑将一条直线以方 ...

  5. Mybatis【17】-- Mybatis自关联查询一对多查询

    注:代码已托管在GitHub上,地址是:https://github.com/Damaer/Mybatis-Learning ,项目是mybatis-13-oneself-one2many,需要自取, ...

  6. 编译器-FIRST集合

      语法分析器的两个重要函数 FIRST和FOLLOW FIRST的定义 FIRST(α),可从α推导得到的串的首符号的集合 1.如果X是一个终结符,那么FIRST(X) = X 2.如果X是一个非终 ...

  7. 让低版本gitlab焕新 —— 如何在低版本gitlab上实现高版本API功能

    前言:本文主要记录了基于低版本gitlab(v3 api)实现in-line comment功能的过程中踩过的坑及相应的解决方案,理论上其他低版本gitlab不具备的API都可以参照此类方法进行实现( ...

  8. 腾讯云 CHDFS 助力微信秒级异常检测

    微信全景监控平台介绍 微信全景监控平台,是微信的多维指标 OLAP 监控以及数据分析平台.支持自定义多维度指标上报,海量数据实时上卷下钻分析,提供了秒级异常检测告警能力. 项目高效支撑了视频号.微信支 ...

  9. TensorFlow 中 conv2d 的确切含义

    在读: <TensorFlow:实战Google深度学习框架> 才云科技Caicloud, 郑泽宇, 顾思宇[摘要 书评 试读]图书https://www.amazon.cn/gp/pro ...

  10. django生命周期流程图与django路由层

    目录 一.django请求生命周期流程图 二.django路由层 1.路由匹配 2.转换器 3.正则匹配 不同版本的区别 正则匹配斜杠导致的区别 4.正则匹配的无名有名分组 分组匹配 无名分组 有名分 ...