[轉]redis服務器與客戶端保活參數(tcp-keepalive)設置

最近使用redis的list作跨進程的消息隊列,客戶端使用的是redis-cplusplus-client.這個client庫仍是蠻好用的,提供了和redis命令行一致的接口,很方便。git

使用過程當中發現下面一個問題。github

我有多個客戶端鏈接同一數據庫,client從redis中blpop數據,設置超時爲5秒。按說沒什麼問題,客戶端也很少,不會對數據庫形成什麼壓力。但運行一段時間後,client就從redis取不到數據了。redis

首先想到的是,是否是數據庫鏈接斷開了。從redis和client兩側查看6379端口的tcp鏈接,發現確實部分client的鏈接沒了。可是客戶端居然沒有異常,還在那傻傻的blpop!看來這個第三方庫仍是作得不夠完善。數據庫

一個解決辦法是,client和redis之間不保持長鏈接,每次操做都從新鏈接。可行,可是too simple。tcp

後來查看了一下redis的配置文件,發現有一個tcp-keepalive的選項。ui

# TCP keepalive.
#
# If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence
# of communication. This is useful for two reasons:
#
# 1) Detect dead peers.
# 2) Take the connection alive from the point of view of network
# equipment in the middle.
#
# On Linux, the specified value (in seconds) is the period used to send ACKs.
# Note that to close the connection the double of the time is needed.
# On other kernels the period depends on the kernel configuration.
#
# A reasonable value for this option is 60 seconds.
tcp-keepalive 0this

就是用來定時向client發送tcp_ack包來探測client是否存活的。默認不探測,官方建議值爲60秒。那就試試吧。命令行

如此設置,觀察一段時間後發現client和redis之間的鏈接一直保持着。管用!接口

更多個人文章,請訪問:零一積流(www.it-refer.com)隊列

相關文章
相關標籤/搜索