`
jinnianshilongnian
  • 浏览: 21434233 次
  • 性别: Icon_minigender_1
博客专栏
5c8dac6a-21dc-3466-8abb-057664ab39c7
跟我学spring3
浏览量:2404982
D659df3e-4ad7-3b12-8b9a-1e94abd75ac3
Spring杂谈
浏览量:2997639
43989fe4-8b6b-3109-aaec-379d27dd4090
跟开涛学SpringMVC...
浏览量:5631433
1df97887-a9e1-3328-b6da-091f51f886a1
Servlet3.1规范翻...
浏览量:257561
4f347843-a078-36c1-977f-797c7fc123fc
springmvc杂谈
浏览量:1593147
22722232-95c1-34f2-b8e1-d059493d3d98
hibernate杂谈
浏览量:248965
45b32b6f-7468-3077-be40-00a5853c9a48
跟我学Shiro
浏览量:5847500
Group-logo
跟我学Nginx+Lua开...
浏览量:698136
5041f67a-12b2-30ba-814d-b55f466529d5
亿级流量网站架构核心技术
浏览量:780438
社区版块
存档分类
最新评论

第五章 常用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

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 = 6660
local ok, err = red:connect(ip, port)
if not ok then
    ngx.say("connect to redis error : ", err)
    return close_redis(red)
end
--调用API进行处理
ok, err = red:set("msg", "hello world")
if not ok then
    ngx.say("set msg error : ", err)
    return close_redis(red)
end

--调用API获取数据
local resp, err = red:get("msg")
if not resp then
    ngx.say("get msg error : ", err)
    return close_redis(red)
end
--得到的数据为空处理
if resp == ngx.null then
    resp = ''  --比如默认值
end
ngx.say("msg : ", resp)

close_redis(red)

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

 

2、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.2/lua_redis_basic进行测试,正常情况得到如下信息

msg : hello world

 

2、连接池

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

我们只需要将之前的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

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

 

此处假设调用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、修改之前的代码片段

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

1、直接eval:

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

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

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 = "127.0.0.1",
    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配置文件

     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.2/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

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

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

upstream backend {
    server s.taobao.com;
    keepalive 100;
}

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

 

2、在example.conf配置如下location

     location ~ /proxy/(.*) {
        internal;
        proxy_pass http://backend/$1$is_args$args;
     }

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

 

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

     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.2/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;来不传递请求头。

 

6
0
分享到:
评论
10 楼 xcmzh 2017-11-01  
xcmzh 写道
Aceslup 写道
test_http_2 代码完全一样,就是测试时是404。搞不懂出错在哪。

我得到的是如下错误,感觉backend没有被解析成upstream 里面的 taobaoURL,请问你的问题和我一样吗?解决了吗?
404 Not Found

The requested URL was not found on this server. Sorry for the inconvenience.
Please report this message and include the following information to us.
Thank you very much!

URL: http://backend/search?q=hello
Server: aserver011135097184.center.et2
Date: 2017/10/31 23:55:37

配置成这样就好了,不然 host一直是backend
location ~ /proxy/(.*) {
        internal;
        proxy_pass http://backend/$1$is_args$args;
        proxy_set_header Host            $host;
        proxy_set_header X-Forwarded-For $remote_addr;
    }
9 楼 xcmzh 2017-11-01  
Aceslup 写道
test_http_2 代码完全一样,就是测试时是404。搞不懂出错在哪。

我得到的是如下错误,感觉backend没有被解析成upstream 里面的 taobaoURL,请问你的问题和我一样吗?解决了吗?
404 Not Found

The requested URL was not found on this server. Sorry for the inconvenience.
Please report this message and include the following information to us.
Thank you very much!

URL: http://backend/search?q=hello
Server: aserver011135097184.center.et2
Date: 2017/10/31 23:55:37
8 楼 Aceslup 2017-10-25  
test_http_2 代码完全一样,就是测试时是404。搞不懂出错在哪。
7 楼 blueskyzs 2017-01-19  
jing3232 写道
请问,lua脚本接连mysql,用域名的怎么弄?没有IP的地址,只有域名的。
大神求解啊。

dns域名解析
6 楼 jing3232 2017-01-13  
请问,lua脚本接连mysql,用域名的怎么弄?没有IP的地址,只有域名的。
大神求解啊。
5 楼 hyhy01 2016-12-29  
test_redis_baisc.lua
打错字了
应该是test_redis_basic.lua
4 楼 jinnianshilongnian 2016-09-19  
tylerpiece 写道
local resp, err = red:get("msg") 
if not resp then 
    ngx.say("get msg error : ", err) 
    return close_reedis(red) 
end

close_reedis多了一个e~~~

收到
3 楼 tylerpiece 2016-09-19  
local resp, err = red:get("msg") 
if not resp then 
    ngx.say("get msg error : ", err) 
    return close_reedis(red) 
end

close_reedis多了一个e~~~
2 楼 totola147 2015-11-05  
if not ok then 
    ngx.say("connect to redis error : ", err) 
    return close_redis(red) 
end


这部分应该不用调用close_redis 因为连接失败了   比如我使用了错误的ip 或port
1 楼 focus2008 2015-10-05  
请教下,为什么都需要加 db:set_timeout(1000) 这一句?

相关推荐

Global site tag (gtag.js) - Google Analytics