原文地址:http://my.oschina.net/hncscwc/blog/195343
heartbeat通常用来检测通信的对端是否存活(未正常关闭socket连接而异常crash)。其基本原理是检测对应的socket连接上数据的收发是否正常,如果一段时间内没有收发数据,则向对端发送一个心跳检测包,如果一段时间内没有回应则认为心跳超时,即认为对端可能异常crash了。
rabbitmq也不例外,heatbeat在客户端和服务端之间用于检测对端是否正常,即客户端与服务端之间的tcp链接是否正常。
1. heartbeat检测时间间隔的设置
1). 服务端的设置
heartbeat检测时间间隔可在配置文件rabbitmq.config中增加配置项{heartbeat,Timeout}进行配置,其中Timeout指定时间间隔,单位为秒。
例如:
如果没有进行配置,默认的时间间隔为600秒(最新版本3.2.2修改为580秒)
在rabbit.app中有heartbeat的配置项。
2). 客户端的设置
根据AMQP协议,rabbitmq会通过connection.tune信令将heartbeat检测时间间隔告知客户端,客户端可以根据需要重新设置该值,并通过Connection.tune-ok信令将时间间隔再告诉给rabbitmq,rabbitmq会以客户端的时间作为该tcp连接上heartbeat检测的间隔时间。
这里要注意的是:如果时间间隔配置为0,则表示不启用heartbeat检测。
C客户端里:
AMQP_CALL amqp_login(amqp_connection_state_t state, char const *vhost,
int channel_max, int frame_max, int heartbeat,
amqp_sasl_method_enum sasl_method, ...);
参数heartbeat参数表示心跳频率,60则表示每60S发一次心跳包
如果启用了rabbitmq_management的话,从web控制台可以看到客户端的检测的时间间隔。
2. heartbeat的实现
rabbitmq在收到来自客户端的connection.tune-ok信令后,启用心跳检测,rabbitmq会为每个tcp连接创建两个进程用于心跳检测,一个进程定时检测tcp连接上是否有数据发送(这里的发送是指rabbitmq发送数据给客户端),如果一段时间内没有数据发送给客户端,则发送一个心跳包给客户端,然后循环进行下一次检测;另一个进程定时检测tcp连接上是否有数据的接收,如果一段时间内没有收到任何数据,则判定为心跳超时,最终会关闭tcp连接。另外,rabbitmq的流量控制机制可能会暂停heartbeat检测,这里不展开描述。
涉及的源码:
01 | start(SupPid, Sock, SendTimeoutSec, |
02 | SendFun, ReceiveTimeoutSec, ReceiveFun) -> |
04 | {ok, Sender} = start_heartbeater(SendTimeoutSec, SupPid, Sock, |
05 | SendFun, heartbeat_sender, |
06 | start_heartbeat_sender), |
08 | {ok, Receiver} = start_heartbeater(ReceiveTimeoutSec, SupPid, |
11 | start_heartbeat_receiver), |
14 | start_heartbeat_sender(Sock, TimeoutSec, SendFun) -> |
15 | %% the 'div 2' is there so that we don't end up waiting for |
16 | %% nearly 2 * TimeoutSec before sending a heartbeat in the |
18 | heartbeater({Sock, TimeoutSec * 1000 div 2 , send_oct, , |
19 | fun () -> SendFun(), continue end}). |
21 | start_heartbeat_receiver(Sock, TimeoutSec, ReceiveFun) -> |
22 | %% we check for incoming data every interval, and time out after |
23 | %% two checks with no change. As a result we will time out |
24 | %% between 2 and 3 intervals after the last data has been |
26 | heartbeater({Sock, TimeoutSec * 1000 , recv_oct, 1 , |
27 | fun () -> ReceiveFun(), stop end}). |
29 | heartbeater({Sock, TimeoutMillisec, |
30 | StatName, Threshold, Handler} = Params, |
32 | {StatVal, SameCount} = State) -> |
33 | Recurse = fun (State1) -> heartbeater(Params, Deb, State1) end, |
37 | after TimeoutMillisec -> |
38 | case rabbit_net:getstat(Sock, [StatName]) of |
39 | {ok, [{StatName, NewStatVal}]} -> |
41 | if NewStatVal =/= StatVal -> |
43 | Recurse({NewStatVal, }); |
44 | %%未达到指定次数, 发送为 , 接收为 1 |
45 | SameCount < Threshold -> |
47 | Recurse({NewStatVal, SameCount + 1 }); |
50 | %%对于发送检测超时, 向客户端发送heartbeat包 |
51 | %%对于接收检测超时, 向父进程发送超时通知 |
57 | continue -> Recurse({NewStatVal, }) |
收发检测的时候利用了inet模块的getstat,查看socket的统计信息
recv_oct: 查看socket上接收的字节数
send_oct: 查看socket上发送的字节数
inet详细见这里: http://www.erlang.org/doc/man/inet.html