前言
Netty心跳重连的代码,需要解决以下几个问题
1)ChannelPipeline中的ChannelHandlers的维护,首次连接和重连都需要对ChannelHandlers进行管理
2)重连对象的管理,也就是bootstrap对象的管理
3)重连机制编写
下面是代码实现...
一.客户端
重连机制主要是在客户端来实现,下面直接上代码
public class HeartClient {
public static void main(String[] args){
new HeartClient().init("localhost",8080);
}
public void init(String address,int port){
NioEventLoopGroup workerGroup = new NioEventLoopGroup(1);
Bootstrap bootstrap = new Bootstrap();
//触发发送心跳包的类
ConnectorIdleStateTrigger idleStateTrigger = new ConnectorIdleStateTrigger();
//netty提供的HashedWheelTimer 主要用来高效处理大量定时任务
// 且任务对时间精度要求相对不高, 比如链接超时管理等场景, 缺点是内存占用相对较高.
HashedWheelTimer timer = new HashedWheelTimer();
bootstrap.group(workerGroup).
option(ChannelOption.TCP_NODELAY,true).
channel(NioSocketChannel.class).
handler(new LoggingHandler());
//顾名思义 监视连接的类,重连机制主要靠他
ConnectionWatchdog connectionWatchdog = new ConnectionWatchdog(bootstrap,timer,address,port) {
@Override
public ChannelHandler[] handler() {
return new ChannelHandler[]{
this,
new IdleStateHandler(0, 5, 0),
new MessageEncoder(),
new MessageDecoder(1 << 20, 9, 4, 0, 0, false),
idleStateTrigger,
new HeartClientHanlder()
};
}
};
ChannelFuture future;
try {
synchronized (bootstrap){
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(connectionWatchdog.handler());
}
});
//进行连接
future = bootstrap.connect(new InetSocketAddress(address,port));
}
future.sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
主要用于重连的时候复用ChannelHandler
public interface ChannelHandlerHolder {
ChannelHandler[] handler();
}
最最关键的来了,ConnectionWatchdog 可以去观察链路是否断了,如果断了,进行循环的断线重连操作
@ChannelHandler.Sharable
public abstract class ConnectionWatchdog extends ChannelInboundHandlerAdapter implements ChannelHandlerHolder , TimerTask {
//尝试次数
private int attempts;
//bootstrap对象,重连的时候依旧需要这个对象
private Bootstrap bootstrap;
//是否重连
boolean reconnect = true;
//执行重连任务的调度器
private Timer timer;
//地址 端口号
private String address;
private int port;
public ConnectionWatchdog(Bootstrap bootstrap, Timer timer, String address, int port) {