通常情況下,我們每個操作 Redis 的指令都以一個 TCP 請求發送給 Redis,這樣的做法簡單直覺。然而,當我們有連續多個指令需要發送給 Redis 時,如果每個指令都以一個資料包發送給 Redis,将會降低服務端的并發能力。
為什麼呢?大家知道每發送一個 TCP 封包,會存在網絡延時及作業系統的處理延時。大部分情況下,網絡延時要遠大于 CPU 的處理延時。如果一個簡單的指令就以一個 TCP 封包發出,網絡延時将成為系統性能瓶頸,使得服務端的并發數量上不去。
首先檢查你的代碼,是否明确完整使用了 Redis 的長連接配接機制。作為一個服務端程式員,要對長連接配接的使用有一定了解,在條件允許的情況下,一定要開啟長連接配接。驗證方式也比較簡單,直接用 tcpdump 或 wireshark 抓包分析一下網絡資料即可。
set_keepalive的參數:按照業務正常運轉的并發數量設定,不建議使用峰值情況設定。
如果我們确定開啟了長連接配接,發現這時候 Redis 的 CPU 的占用率還是不高,在這種情況下,就要從 Redis 的使用方法上進行優化。
如果我們可以把所有單次請求,壓縮到一起,如下圖:
# you do not need the following line if you are using
# the ngx_openresty bundle:
lua_package_path "/path/to/lua-resty-redis/lib/?.lua;;";
server {
location /withoutpipeline {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
-- or connect to a unix domain socket file listened
-- by a redis server:
-- local ok, err = red:connect("unix:/path/to/redis.sock")
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local ok, err = red:set("cat", "Marry")
ngx.say("set result: ", ok)
local res, err = red:get("cat")
ngx.say("cat: ", res)
ok, err = red:set("horse", "Bob")
ngx.say("set result: ", ok)
res, err = red:get("horse")
ngx.say("horse: ", res)
-- put it into the connection pool of size 100,
-- with 10 seconds max idle time
local ok, err = red:set_keepalive(10000, 100)
if not ok then
ngx.say("failed to set keepalive: ", err)
return
end
}
}
location /withpipeline {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
-- or connect to a unix domain socket file listened
-- by a redis server:
-- local ok, err = red:connect("unix:/path/to/redis.sock")
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("failed to connect: ", err)
return
end
red:init_pipeline()
red:set("cat", "Marry")
red:set("horse", "Bob")
red:get("cat")
red:get("horse")
local results, err = red:commit_pipeline()
if not results then
ngx.say("failed to commit the pipelined requests: ", err)
return
end
for i, res in ipairs(results) do
if type(res) == "table" then
if not res[1] then
ngx.say("failed to run command ", i, ": ", res[2])
else
-- process the table value
end
else
-- process the scalar value
end
end
-- put it into the connection pool of size 100,
-- with 10 seconds max idle time
local ok, err = red:set_keepalive(10000, 100)
if not ok then
ngx.say("failed to set keepalive: ", err)
return
end
}
}
}