当服务端进行断电重启之后,netty客户端不进行重连,需要重启项目,才会触发初始化连接机制
// 连接代码
@PostConstruct
public void start() {
if (Boolean.FALSE.equals(this.enable)) {
return;
}
try {
eventLoopGroup = new NioEventLoopGroup();
bootstrap = new Bootstrap()
.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline cp = ch.pipeline();
cp.addLast(new CockpitInBoundHandler());
cp.addLast(new ConnectHandler(CockpitNettyClient.this));
}
});
this.connect();
} catch (Exception e) {
log.error("netty客户端启动异常:", e);
}
}
public void connect() throws InterruptedException {
channelFuture = bootstrap.connect(this.cockpitIp, this.cockpitPort);
channelFuture.addListener((ChannelFutureListener) future -> {
log.info("重新连接失败");
boolean success = future.isSuccess();
if (!success) {
future.channel().eventLoop().schedule(() -> {
log.info("重新连接失败");
try {
connect();
} catch (InterruptedException e) {
log.error("重新连接失败");
}
}, 4, TimeUnit.SECONDS);
} else {
log.info("重新连接失败");
}
});
}
// 重连代码
public class ConnectHandler extends ChannelInboundHandlerAdapter {
private CockpitNettyClient cockpitNettyClient;
public ConnectHandler(CockpitNettyClient chatClient) {
this.cockpitNettyClient = chatClient;
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
cockpitNettyClient.connect();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.error("[ConnectHandler]连接异常", cause);
}
}