1.heartbeat检测时间间隔可在配置文件rabbitmq.config中增加配置项{heartbeat,Timeout}进行配置,其中Timeout指定时间间隔,单位为秒,另外客户端也可以配置heartbeat时间。
如果服务端没有配置
默认代理心跳时间:
RabbitMQ 3.2.2:580秒
RabbitMQ 3.5.5:60秒
rabbitmq在收到来自客户端的connection.tune-ok信令后,启用心跳检测,rabbitmq会为每个tcp连接创建两个进程用于心跳检测,一个进程定时检测tcp连接上是否有数据发送(这里的发送是指rabbitmq发送数据给客户端),如果一段时间内没有数据发送给客户端,则发送一个心跳包给客户端,然后循环进行下一次检测;另一个进程定时检测tcp连接上是否有数据的接收,如果一段时间内没有收到任何数据,则判定为心跳超时,最终会关闭tcp连接。另外,rabbitmq的流量控制机制可能会暂停heartbeat检测,这里不展开描述。
start(SupPid, Sock, SendTimeoutSec,
SendFun, ReceiveTimeoutSec, ReceiveFun) ->
%%数据发送检测进程
{ok, Sender} = start_heartbeater(SendTimeoutSec, SupPid, Sock,
SendFun, heartbeat_sender,
start_heartbeat_sender),
%%数据接收检测进程
{ok, Receiver} = start_heartbeater(ReceiveTimeoutSec, SupPid,
Sock, ReceiveFun,
heartbeat_receiver,
start_heartbeat_receiver),
{Sender, Receiver}.
start_heartbeat_sender(Sock, TimeoutSec, SendFun) ->
%% the ‘div 2‘ is there so that we don‘t end up waiting for
%% nearly 2 * TimeoutSec before sending a heartbeat in the
%% boundary case
heartbeater({Sock, TimeoutSec * 1000 div 2, send_oct, 0,
fun () -> SendFun(), continue end}).
start_heartbeat_receiver(Sock, TimeoutSec, ReceiveFun) ->
%% we check for incoming data every interval, and time out after
%% two checks with no change. As a result we will time out
%% between 2 and 3 intervals after the last data has been
%% received
heartbeater({Sock, TimeoutSec * 1000, recv_oct, 1,
fun () -> ReceiveFun(), stop end}).
heartbeater({Sock, TimeoutMillisec,
StatName, Threshold, Handler} = Params,
Deb,
{StatVal, SameCount} = State) ->
Recurse = fun (State1) -> heartbeater(Params, Deb, State1) end,
receive
...
%% 定时检测
after TimeoutMillisec ->
case rabbit_net:getstat(Sock, [StatName]) of
{ok, [{StatName, NewStatVal}]} ->
%% 收发数据有变化
if NewStatVal =/= StatVal ->
%%重新开始检测
Recurse({NewStatVal, 0});
%%未达到指定次数, 发送为0, 接收为1
SameCount < Threshold ->
%%计数加1, 再次检测
Recurse({NewStatVal, SameCount + 1});
%%heartbeat超时
true ->
%%对于发送检测超时, 向客户端发送heartbeat包
%%对于接收检测超时, 向父进程发送超时通知
%%由父进程触发tcp关闭等操作
case Handler() of
%%接收检测超时
stop -> ok;
%%发送检测超时
continue -> Recurse({NewStatVal, 0})
end;
...