OpenResty-Lua模块开发

原创地址:http://jinnianshilongnian.iteye.com/blog/2190344

 

常用命令

# vi /usr/local/nginx/conf/nginx.conf

# vi /usr/server/example/example.conf

# /usr/local/nginx/sbin/nginx  -s reload &  tail -f /usr/local/nginx/logs/error.log

 

目录:

1.OpenRestry(Nginx+Lua)开发环境

 

2.OpenRestry开发入门

 

3.Lua模块开发

3.1 常用Lua开发库1-redis、mysql、http客户端 附-Redis/SSDB+Twemproxy安装与使用

3.2 常用Lua开发库2-JSON库、编码转换、字符串处理

3.3 常用Lua开发库3-模板渲染

 

4.实战

4.1 Web开发实战1——HTTP服务

4.2 Web开发实战2——商品详情页

4.3 流量复制/AB测试/协程

 

 一.Lua模块开发

在实际开发中,不可能把所有代码写到一个大而全的lua文件中,需要进行分模块开发;而且模块化是高性能Lua应用的关键。

使用require第一次导入模块后,所有Nginx进程全局共享模块的数据和代码,每个Worker进程需要时会得到此模块的一个副本(Copy-On-Write),即模块可以认为是每Worker进程共享而不是每Nginx Server共享;

另外注意之前我们使用init_by_lua中初始化的全局变量是每请求复制一个;

如果想在多个Worker进程间共享数据可以使用ngx.shared.DICT或如Redis之类的存储。

 

1.大量第三方开发库如cjson、redis客户端、mysql客户端:/usr/server/example/lualib

 # ls -l /usr/server/example/lualib

cjson.so

 

resty/

   aes.lua

   core.lua

   dns/

   lock.lua

   lrucache/

   lrucache.lua

   md5.lua

   memcached.lua

   mysql.lua

   random.lua

   redis.lua

   ……

 

2.如何使用

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

    #lua模块路径,其中”;;”表示默认搜索路径,默认到/usr/local/nginx下找  

    lua_package_path   "/usr/server/example/lualib/?.lua;;";  #lua 模块  

    lua_package_cpath "/usr/server/example/lualib/?.so;;";  #c模块   

 

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

 

    local cjson = require(“cjson”)  

    local redis = require(“resty.redis”)   

 

3.案例:

(1) 开发一个简单的lua模块。

# vi  /usr/server/example/lualib/module1.lua

    local count = 0  

    local function hello()  

       count = count + 1  

       ngx.say("count : ", count)  

    end  

      

    local _M = {  

       hello = hello  

    }  

      

    return _M  

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

 

(2) 使用该模块

test_module_1.lua

#  vi /usr/server/example/lua/test_module_1.lua

 

    local module1 = require("module1")     

    module1.hello()  

 

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

 

(3)配置example.conf

# vi  /usr/server/example/example.conf

    location /lua_module_1 {  

        default_type 'text/html';  

        lua_code_cache on;  

        content_by_lua_file /usr/server/example/lua/test_module_1.lua;  

    }  

 

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

count : 1

count :2

……

count :N

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

 

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

 

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

 

 

目前对于互联网公司不使用Redis的很少,Redis不仅仅可以作为key-value缓存,而且提供了丰富的数据结果如set、list、map等,可以实现很多复杂的功能;但是Redis本身主要用作内存缓存,不适合做持久化存储,因此目前有如SSDB、ARDB等,还有如京东的JIMDB,它们都支持Redis协议,可以支持Redis客户端直接访问;而这些持久化存储大多数使用了如LevelDB、RocksDB、LMDB持久化引擎来实现数据的持久化存储;京东的JIMDB主要分为两个版本:LevelDB和LMDB,而我们看到的京东商品详情页就是使用LMDB引擎作为存储的,可以实现海量KV存储;当然SSDB在京东内部也有些部门在使用;另外调研过得如豆瓣的beansDB也是很不错的。具体这些持久化引擎之间的区别可以自行查找资料学习。

 

二.常用Lua开发库1-redis、mysql、http客户端 附-Redis/SSDB+Twemproxy安装与使用

1.附-Redis/SSDB+Twemproxy安装与使用

1.1Redis安装与使用

 见:Redis介绍及安装集群使

1.2 twemproxy

见:Twemproxy-缓存代理分片机制 编辑

因为我们所有的Twemproxy配置文件规则都是一样的,因此我们应该将其移到我们项目中。

cp /usr/servers/twemproxy-0.4.0/conf/nutcracker.yml  /usr/example/ 

 

6.Redis执行Lua脚本

Redis客户端支持解析和处理lua脚本,因为Redis的单线程机制,我们可以借助Lua脚本实现一些原子操作,如扣减库存/红包之类的。此处不建议使用EVAL直接发送lua脚本到客户端,因为其每次都会进行Lua脚本的解析,而是使用SCRIPT LOAD+ EVALSHA进行操作。未来不知道是否会用luajit来代替lua,让redis lua脚本性能更强。

到此基本的Redis知识就讲完了。

 

 1.3 SSDB

见: SSDB介绍与使用

 

三.常用Lua开发库2-JSON库、编码转换、字符串处理

四. 常用Lua开发库3-模板渲染

对于开发来说需要有好的生态开发库来辅助我们快速开发,而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.基本操作

1.1 编辑test_redis_baisc.lua (封装访问Redis服务端的内容)

vi /usr/example/lua/test_redis_basic.lua

 

local function close_redis(red)

        if not red then

                return

        end

        local ok, err = red:close()

        if not ok then

                ngx.say("close redis error : ", err)

        end

end 

 

local redis = require("resty.redis")

 

--创建实例

local red = redis:new()

--设置超时(毫秒)

red:set_timeout(1000)

--建立连接

local ip = "127.0.0.1"

local port = 1111

local ok, err = red:connect(ip, port)

if not ok then

        ngx.say("connect to redis error : ", err)

        return close_redis(red)

end 

 

--调用API获取数据

local resp, err = red:get("msg")

 

--得到的数据为空处理

if resp == ngx.null then

        -- 无数据则调用API处理:访问分布式缓存集群(需建立分布式redis集群),再则发请求到后端服务器

        ok, err = red:set("msg", "hello world1234888")

        if not ok then

                ngx.say("set msg error : ", err)

                return close_redis(red)

        end

        resp = 'hello world1234888'

end

 

ngx.say("msg : ", resp)

 

close_redis(red)

 

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

 

2.example.conf配置文件

vi /usr/example/example.conf

 

     location /lua_redis_basic {  

        default_type 'text/html';  

        lua_code_cache on;  

        content_by_lua_file /usr/example/lua/test_redis_basic.lua;  

    }  

 

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

 

msg : hello world1234888

 

 

 

【连接池】

 

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

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

    local function close_redis(red)  

        if not red then  

            return  

        end  

        --释放连接(连接池实现)  

        local pool_max_idle_time = 10000 --毫秒  

        local pool_size = 100 --连接池大小  

        local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)  

        if not ok then  

            ngx.say("set keepalive error : ", err)  

        end  

    end  

 

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

 

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

 vi /usr/servers/nginx/conf/nginx.conf

#默认连接池大小,默认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。

 

 

 

【pipeline】

pipeline即管道,可以理解为把多个命令打包然后一起发送;MTU(Maxitum Transmission Unit 最大传输单元)为二层包大小,一般为1500字节;而MSS(Maximum Segment Size 最大报文分段大小)为四层包大小,其一般是1500-20(IP报头)-20(TCP报头)=1460字节;

因此假设我们执行的多个Redis命令能在一个报文中传输的话,可以减少网络往返来提高速度。

因此可以根据实际情况来选择走pipeline模式将多个命令打包到一个报文发送然后接受响应,而Redis协议也能很简单的识别和解决粘包。

 

1、修改之前的代码片段

    red:init_pipeline()  

    red:set("msg1", "hello1")  

    red:set("msg2", "hello2")  

    red:get("msg1")  

    red:get("msg2")  

    local respTable, err = red:commit_pipeline()  

      

    --得到的数据为空处理  

    if respTable == ngx.null then  

        respTable = {}  --比如默认值  

    end  

      

    --结果是按照执行顺序返回的一个table  

    for i, v in ipairs(respTable) do  

       ngx.say("msg : ", v, "<br/>")  

    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")可以通过如下两种方式实现:

 

3.1 直接eval:

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

 

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

    local sha1, err = red:script("load",  "return redis.call('get', KEYS[1])");  

    if not sha1 then  

       ngx.say("load script error : ", err)  

       return close_redis(red)  

    end  

    ngx.say("sha1 : ", sha1, "<br/>")  

    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

vi /usr/example/lua/test_mysql.lua

 

local function close_db(db)  

if not db then  

return  

end  

db:close()  

end  

  

local mysql = require("resty.mysql")  

--创建实例  

local db, err = mysql:new()  

if not db then  

ngx.say("new mysql error : ", err)  

return  

end  

--设置超时时间(毫秒)  

db:set_timeout(1000)  

  

local props = {  

host = "192.168.1.121",  

port = 3306,  

database = "mysql",  

user = "root",  

password = "123456"  

}  

  

local res, err, errno, sqlstate = db:connect(props)  

  

if not res then  

   ngx.say("connect to mysql error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  

   return close_db(db)  

end  

  

--删除表  

local drop_table_sql = "drop table if exists test"  

res, err, errno, sqlstate = db:query(drop_table_sql)  

if not res then  

   ngx.say("drop table error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  

   return close_db(db)  

end  

  

--创建表  

local create_table_sql = "create table test(id int primary key auto_increment, ch varchar(100))"  

res, err, errno, sqlstate = db:query(create_table_sql)  

if not res then  

   ngx.say("create table error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  

   return close_db(db)  

end  

  

--插入  

local insert_sql = "insert into test (ch) values('hello')"  

res, err, errno, sqlstate = db:query(insert_sql)  

if not res then  

   ngx.say("insert error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  

   return close_db(db)  

end  

  

res, err, errno, sqlstate = db:query(insert_sql)  

  

ngx.say("insert rows : ", res.affected_rows, " , id : ", res.insert_id, "<br/>")  

  

--更新  

local update_sql = "update test set ch = 'hello2' where id =" .. res.insert_id  

res, err, errno, sqlstate = db:query(update_sql)  

if not res then  

   ngx.say("update error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  

   return close_db(db)  

end  

  

ngx.say("update rows : ", res.affected_rows, "<br/>")  

--查询  

local select_sql = "select id, ch from test"  

res, err, errno, sqlstate = db:query(select_sql)  

if not res then  

   ngx.say("select error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  

   return close_db(db)  

end  

  

  

for i, row in ipairs(res) do  

   for name, value in pairs(row) do  

ngx.say("select row ", i, " : ", name, " = ", value, "<br/>")  

   end  

end  

  

ngx.say("<br/>")  

--防止sql注入  

local ch_param = ngx.req.get_uri_args()["ch"] or ''  

--使用ngx.quote_sql_str防止sql注入  

local query_sql = "select id, ch from test where ch = " .. ngx.quote_sql_str(ch_param)  

res, err, errno, sqlstate = db:query(query_sql)  

if not res then  

   ngx.say("select error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  

   return close_db(db)  

end  

  

for i, row in ipairs(res) do  

   for name, value in pairs(row) do  

ngx.say("select row ", i, " : ", name, " = ", value, "<br/>")  

   end  

end  

  

--删除  

local delete_sql = "delete from test"  

res, err, errno, sqlstate = db:query(delete_sql)  

if not res then  

   ngx.say("delete error : ", err, " , errno : ", errno, " , sqlstate : ", sqlstate)  

   return close_db(db)  

end  

  

ngx.say("delete rows : ", res.affected_rows, "<br/>")  

  

  

close_db(db)  

 

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

    {  

        insert_id = 0,  

        server_status = 2,  

        warning_count = 1,  

        affected_rows = 32,  

        message = nil  

    }  

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

 

 

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

 

    {  

        { id= 1, ch= "hello"},  

        { id= 2, ch= "hello2"}  

    }  

 

null将返回ngx.null。

 

 

2.example.conf配置文件

vi /usr/example/example.conf

    location /lua_mysql {  

       default_type 'text/html';  

       lua_code_cache on;  

       content_by_lua_file /usr/example/lua/test_mysql.lua;  

    }  

 

 

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

    insert rows : 1 , id : 2  

    update rows : 1  

    select row 1 : ch = hello  

    select row 1 : id = 1  

    select row 2 : ch = hello2  

    select row 2 : id = 2  

    select row 1 : ch = hello  

    select row 1 : id = 1  

    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 

    cd /usr/example/lualib/resty/  

    wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http_headers.lua  

    wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http.lua  

 

2、test_http_1.lua

vi /usr/example/lua/test_http_1.lua

 

local http = require("resty.http")  

--创建http客户端实例  

local httpc = http.new()  

  

local resp, err = httpc:request_uri("http://s.taobao.com", {  

method = "GET",  

path = "/search?q=hello",  

headers = {  

["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36"  

}  

})  

  

if not resp then  

ngx.say("request error :", err)  

return  

end  

  

--获取状态码  

ngx.status = resp.status  

  

--获取响应头  

for k, v in pairs(resp.headers) do  

if k ~= "Transfer-Encoding" and k ~= "Connection" then  

ngx.header[k] = v  

end  

end  

--响应体  

ngx.say(resp.body)  

  

httpc:close()  

 

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

 

3.example.conf配置文件

vi /usr/example/example.conf 

    location /lua_http_1 {  

       default_type 'text/html';  

       lua_code_cache on;  

       content_by_lua_file /usr/example/lua/test_http_1.lua;  

    }  

 

4.在nginx.conf中的http部分添加如下指令来做DNS解析

vi /usr/servers/nginx/conf/nginx.conf

    resolver 8.8.8.8;  

记得要配置DNS解析器resolver 8.8.8.8,否则域名是无法解析的。request error :no resolver defined to resolve "s.taobao.com" 

 

5.访问如http://192.168.1.108/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配置

vi /usr/servers/nginx/conf/nginx.conf

 

    upstream backend {  

        server s.taobao.com;  

        keepalive 100;  

    }  

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

 

2.在example.conf配置如下location

vi /usr/example/example.conf 

    location ~ /proxy/(.*) {  

       internal;  

       proxy_pass http://backend/$1$is_args$args;  

    }  

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

 

3.test_http_2.lua

vi /usr/example/lua/test_http_2.lua

 

local resp = ngx.location.capture("/proxy/search", {  

method = ngx.HTTP_GET,  

args = {q = "hello"}  

  

})  

if not resp then  

ngx.say("request error :", err)  

return  

end  

ngx.log(ngx.ERR, tostring(resp.status))  

  

--获取状态码  

ngx.status = resp.status  

  

--获取响应头  

for k, v in pairs(resp.header) do  

if k ~= "Transfer-Encoding" and k ~= "Connection" then  

ngx.header[k] = v  

end  

end  

--响应体  

if resp.body then  

ngx.say(resp.body)  

end  

 

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

 

 

4.example.conf配置文件

vi /usr/example/example.conf

 

    location /lua_http_2 {  

       default_type 'text/html';  

       lua_code_cache on;  

       content_by_lua_file /usr/example/lua/test_http_2.lua;  

    }  

 

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

 

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

 

不过因为继承在当前请求的请求头,所以可能会存在一些问题,比较常见的就是gzip压缩问题,ngx.location.capture不会解压缩后端服务器的GZIP内容,解决办法可以参考https://github.com/openresty/lua-nginx-module/issues/12;因为我们大部分这种http调用的都是内部服务,因此完全可以在proxy location中添加proxy_pass_request_headers off;来不传递请求头。

 

 

 

 

 

 

 

 

 

 

 

 

********3-2.常用Lua开发库2-JSON库、编码转换、字符串处理*******

【JSON库】

 

 

在进行数据传输时JSON格式目前应用广泛,因此从Lua对象与JSON字符串之间相互转换是一个非常常见的功能;

目前Lua也有几个JSON库,本人用过cjson、dkjson。

(1) cjson的语法严格(比如unicode \u0020\u7eaf),要求符合规范否则会解析失败(如\u002)

(2) dkjson相对宽松,当然也可以通过修改cjson的源码来完成一些特殊要求。而在使用dkjson时也没有遇到性能问题

目前使用的就是dkjson。使用时要特别注意的是大部分JSON库都仅支持UTF-8编码;因此如果你的字符编码是如GBK则需要先转换为UTF-8然后进行处理。

 

1.cjson

 

1.1、test_cjson.lua

vi /usr/example/lua/test_cjson.lua

 

 

local cjson = require("cjson")  

  

--lua对象到字符串  

local obj = {  

id = 1,  

name = "zhangsan",  

age = nil,  

is_male = false,  

hobby = {"film", "music", "read"}  

}  

  

local str = cjson.encode(obj)  

ngx.say(str, "<br/>")  

  

--字符串到lua对象  

str = '{"hobby":["film","music","read"],"is_male":false,"name":"zhangsan","id":1,"age":null}'  

local obj = cjson.decode(str)  

  

ngx.say(obj.age, "<br/>")  

ngx.say(obj.age == nil, "<br/>")  

ngx.say(obj.age == cjson.null, "<br/>")  

ngx.say(obj.hobby[1], "<br/>")  

  

  

--循环引用  

obj = {  

   id = 1  

}  

obj.obj = obj  

-- Cannot serialise, excessive nesting  

--ngx.say(cjson.encode(obj), "<br/>")  

local cjson_safe = require("cjson.safe")  

--nil  

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

 vi /usr/example/example.conf

 

    location ~ /lua_cjson {  

       default_type 'text/html';  

       lua_code_cache on;  

       content_by_lua_file /usr/example/lua/test_cjson.lua;  

    }  

 

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

    {"hobby":["film","music","read"],"is_male":false,"name":"zhangsan","id":1}  

    null  

    false  

    true  

    film  

    nil  

 

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

 

 

 

2. dkjson

 

2.1、下载dkjson库 

    cd /usr/example/lualib/  

    wget http://dkolf.de/src/dkjson-lua.fsl/raw/dkjson.lua?name=16cbc26080996d9da827df42cb0844a25518eeb3 -O dkjson.lua  

 

2.2、test_dkjson.lua

vi /usr/example/lua/test_dkjson.lua

 

local dkjson = require("dkjson")  

  

--lua对象到字符串  

local obj = {  

id = 1,  

name = "zhangsan",  

age = nil,  

is_male = false,  

hobby = {"film", "music", "read"}  

}  

  

local str = dkjson.encode(obj, {indent = true})  

ngx.say(str, "<br/>")  

  

--字符串到lua对象  

str = '{"hobby":["film","music","read"],"is_male":false,"name":"zhangsan","id":1,"age":null}'  

local obj, pos, err = dkjson.decode(str, 1, nil)  

  

ngx.say(obj.age, "<br/>")  

ngx.say(obj.age == nil, "<br/>")  

ngx.say(obj.hobby[1], "<br/>")  

  

--循环引用  

obj = {  

   id = 1  

}  

obj.obj = obj  

--reference cycle  

--ngx.say(dkjson.encode(obj), "<br/>")                                       

 

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

 

2.3、example.conf配置文件

 vi /usr/example/example.conf

 

    location ~ /lua_dkjson {  

       default_type 'text/html';  

       lua_code_cache on;  

       content_by_lua_file /usr/example/lua/test_dkjson.lua;  

    }  

 

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

 

    { "hobby":["film","music","read"], "is_male":false, "name":"zhangsan", "id":1 }  

    nil  

    true  

    film  

 

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

 

 

 

3.编码转换

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

 

安装lua-iconv

可以通过如下两种方式:

 

ubuntu下可以使用如下方式

apt-get install luarocks  

luarocks install lua-iconv   

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  

tar -xvf lua-iconv-7.tar.gz  

cd lua-iconv-7  

[2]gcc -O2 -fPIC -I/usr/include/lua5.1 -c luaiconv.c -o luaiconv.o -I/usr/include  

gcc -shared -o iconv.so -L/usr/local/lib luaiconv.o -L/usr/lib  

cp iconv.so  /usr/example/lualib/ 

 

说明:

[1]文件在以上地址报错404,手动下载上传的 

[2]报错:luaiconv.c:43:3: error: #error "Unsuported Lua version. You must use Lua >= 5.1" =====》未解决啊

 

3.1 test_iconv.lua

vi /usr/example/lua/test_iconv.lua

    ngx.say("中文")  

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

 

3.2 example.conf配置文件

vi /usr/example/example.conf

 

    location ~ /lua_iconv {  

       default_type 'text/html';  

       charset gbk;  

       lua_code_cache on;  

       content_by_lua_file /usr/example/lua/test_iconv.lua;  

    }  

 

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

 

3.3 访问 http://192.168.1.108/lua_iconv 会发现输出乱码;

 

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

vi /usr/example/lua/test_iconv.lua

 

local iconv = require("iconv")  

local togbk = iconv.new("gbk", "utf-8")  

local str, err = togbk:iconv("中文")  

ngx.say(str)  

 

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

 

 /usr/example/lua/test_iconv.lua:1: module 'iconv' not found ---> 因为上面的问题没有解决

[报错: 有如下可能出现的错误]

    nil     

        没有错误成功。  

    iconv.ERROR_NO_MEMORY  

        内存不足。  

    iconv.ERROR_INVALID  

        有非法字符。  

    iconv.ERROR_INCOMPLETE  

        有不完整字符。  

    iconv.ERROR_FINALIZED  

        使用已经销毁的转换器,比如垃圾回收了。  

    iconv.ERROR_UNKNOWN   

        未知错误  

 

方案:

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

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

 

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

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

 

 

 

4.位运算

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

 

4.1 test_bit.lua 

vi /usr/example/lua/test_bit.lua

 

local bit = require("bit")  

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. 

 

 

 

5. cache

ngx_lua模块本身提供了全局共享内存ngx.shared.DICT可以实现全局共享,另外可以使用如Redis来实现缓存。

另外还一个lua-resty-lrucache实现,其和ngx.shared.DICT不一样的是它是每Worker进程共享,即每个Worker进行会有一份缓存,

而且经过实际使用发现其性能不如ngx.shared.DICT。但是其好处就是不需要进行全局配置。

 

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

vi /usr/example/lualib/mycache.lua   

 

local lrucache = require("resty.lrucache")  

--创建缓存实例,并指定最多缓存多少条目  

local cache, err = lrucache.new(200)  

if not cache then  

   ngx.log(ngx.ERR, "create cache error : ", err)  

end  

  

local function set(key, value, ttlInSeconds)  

cache:set(key, value, ttlInSeconds)  

end  

  

local function get(key)  

return cache:get(key)  

end  

  

local _M = {  

  set = set,  

  get = get  

}  

  

return _M  

 

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

猜你喜欢

转载自zjjndnr.iteye.com/blog/2386893