我有一个场景,我正在使用 netty NIO 建立 TCP 连接,假设服务器出现故障,那么当它再次出现时我如何自动连接到服务器? 或者有什么方法可以在服务器上附加可用性监听器吗?
最佳答案
您可以有一个 DisconnectionHandler
,作为客户端管道上的第一件事,它通过立即尝试重新连接或安排重新连接任务来对 channelInactive
使用react。
例如,
public class DisconnectionHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
/* If shutdown is on going, ignore */
if (channel.eventLoop().isShuttingDown()) return;
ReconnectionTask reconnect = new ReconnectionTask(channel);
reconnect.run();
}
}
ReconnectionTask
应该是这样的:
public class ReconnectionTask implements Runnable, ChannelFutureListener {
Channel previous;
public ReconnectionTask(Channel c) {
this.previous = c;
}
@Override
public void run() {
Bootstrap b = createBootstrap();
b.remoteAddress(previous.remoteAddress())
.connect()
.addListener(this);
}
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
// Will try to connect again in 100 ms.
// Here you should probably use exponential backoff or some sort of randomization to define the retry period.
previous.eventLoop()
.schedule(this, 100, MILLISECONDS);
return;
}
// Do something else when success if needed.
}
}
在此处查看 Exponential Backoff library 的示例.
关于java - netty中如何在断开连接后自动连接到TCP服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36408662/