java通过netty实现心跳机制_聊聊心跳机制及netty心跳实现

我们在使用netty的时候会使用一个参数,ChannelOption.SO_KEEPALIVE为true, 设置好了之后再Linux系统才会对keepalive生效,但是linux里边需要配置几个参数,tcp_keepalive_time, tcp_keepalive_invl, tcp_keepalive_probes,如果不配置的时候都会是默认值。

tcp_keepalive_time 即给一个TCP连接发送心跳包最后的时间间隔某一段时间后继续发送心跳包,允许空闲的时间,然后再次发送心跳包,默认时间为7200秒,即2个小时发一次心跳包。

tcp_keepalive_invl,发送存活探测时候未收到对方回执的时候,需要间隔一段时间继续发送。默认为75秒。

tcp_keepalive_probes,如果发了存活探测的时候没有收到对方的回执,那么需要继续发送探测的次数,此时默认值为9次,也就是未收到回执的时候需要发送9次。

再理一次,间隔tcp_keepalive_time之后发送心跳探测,如果未收到对方回执的时候,需要间隔tcp_keepalive_invl设置的时间继续发送,一共需要发送tcp_keepalive_probes的次数。

这个是Linux系统的配置,如果要使用Linux的此功能需要设置SO_KEEPALIVE为true,同时设置其他几个参数。系统默认的SO_KEEPALIVE为false。因为这些情况的差异,所以netty提供了自己实现心跳的机制。

netty有心跳的实现方法 IdleStateHandler,其中有读空闲时间,写空闲时间,读写空闲时间,只要有一个满足条件会触发userEventTriggered方法。

publicIdleStateHandler(intreaderIdleTimeSeconds,intwriterIdleTimeSeconds,int allIdleTimeSeconds)

定义个消息内容吧,长度为Type的长度1 + 实际内容的长度5 = 6。Length为2个字节,Type为1个类型。

+----------+----------+----------------+

| Length |Type(byte)| Actual Content |

| 0x06 | 1 | "HELLO" |

+----------+----------+----------------+

定义公共的inbound方法,用于进行channelRead, sendPing, sendPong, userEventTriggered 方法。

packagecom.hqs.heartbeat.common;importio.netty.buffer.ByteBuf;importio.netty.channel.ChannelHandlerContext;importio.netty.channel.SimpleChannelInboundHandler;importio.netty.handler.timeout.IdleStateEvent;importjava.util.concurrent.atomic.AtomicInteger;/***@authorhuangqingshi

* @Date 2019-05-11*/

public abstract class CustomeHeartbeatHandler extends SimpleChannelInboundHandler{public static final byte PING = 1;public static final byte PONG = 2;public static final byte CUSTOM_MSG = 3;protectedString name;private AtomicInteger heartbeatCount = new AtomicInteger(0);publicCustomeHeartbeatHandler(String name) {this.name =name;

}

@Overrideprotected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throwsException {if(byteBuf.getByte(2) ==PING) {

sendPong(channelHandlerContext);

}else if(byteBuf.getByte(2) ==PONG) {

System.out.println("get pong msg from " +channelHandlerContext

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值