pipeline即管道,可以理解为把多个命令打包然后一起发送;MTU(Maxitum Transmission Unit 最大传输单元)为二层包大小,一般为1500字节;而MSS(Maximum Segment Size 最大报文分段大小)为四层包大小,其一般是1500-20(IP报头)-20(TCP报头)=1460字节;因此假设我们执行的多个Redis命令能在一个报文中传输的话,可以减少网络往返来提高速度。因此可以根据实际情况来选择走pipeline模式将多个命令打包到一个报文发送然后接受响应,而Redis协议也能很简单的识别和解决粘包。
修改之前的代码段
test_pipeline.lua
-- local function close_redes( 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 function close_redes( red )
if not red then
return
-- 释放连接(连接池实现)
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)
local redis = require("resty.redis")
-- 创建实例
local red = redis:new()
-- 设置超时(毫秒)
red:set_timeout(2000)
-- 建立连接
local ip = "172.19.73.87"
local port = 6379
local ok, err = red:connect(ip, port)
if not ok then
return
local res, err = red:auth("wsy@123456")
if not res then
ngx.say("connect to redis error : ", err)
return
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 = {}
-- 结果是按照执行顺序返回的一个table
for i, v in ipairs(respTable) do
ngx.say("msg : ", v, "<br/>")
close_redes(red)
通过init_pipeline()初始化,然后通过commit_pipieline()打包提交init_pipeline()之后的Redis命令;返回结果是一个lua table,可以通过ipairs循环获取结果;
配置相应location,测试得到的结果
openResty.conf配置文件
location /lua_redis_pipeline {
default_type 'text/html';
lua_code_cache on;
content_by_lua_file /usr/openResty/lua/redis/test_pipeline.lua;
msg : OK
msg : OK
msg : hello1
msg : hello2
Redis Lua脚本
利用Redis单线程特性,可以通过在Redis中执行Lua脚本实现一些原子操作。如之前的red:get(“msg”)可以通过如下两种方式实现:
直接eval:
local resp, err = red:eval("return redis.call('get', KEYS[1])", 1, "msg");
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)
ngx.say("sha1 : ", sha1, "")
local resp, err = red:evalsha(sha1, 1, "msg");
首先通过script load导入脚本并得到一个sha1校验和(仅需第一次导入即可),然后通过evalsha执行sha1校验和即可,这样如果脚本很长通过这种方式可以减少带宽的消耗。
此处仅介绍了最简单的redis lua脚本,更复杂的请参考官方文档学习使用。
另外Redis集群分片算法该客户端没有提供需要自己实现,当然可以考虑直接使用类似于Twemproxy这种中间件实现。