【问题标题】:How to automatically connect to TCP server after disconnection in netty如何在netty中断开连接后自动连接到TCP服务器
【发布时间】:2016-07-24 08:23:04
【问题描述】:

我有一个场景,我正在使用 netty NIO 建立 TCP 连接,假设服务器出现故障而不是当它再次出现时如何自动连接到服务器? 或者有没有办法在服务器上附加可用性监听器?

【问题讨论】:

  • 有趣的问题,但我认为只需对服务器执行 ping 操作即可获得可用性
  • 但在这种情况下,我需要让我的一个线程忙于检查服务器的可用性,让我们看看是否有人对此有任何想法
  • 尝试在处理程序中使用 ChannelInactive 方法
  • 与您创建原始连接的方式相同。不清楚你在问什么。
  • @EJP 但是我怎么能检测到服务器再次启动所以可能会出现服务器在几个小时后恢复的情况,而不是在那种情况下我需要继续重试直到那个时候,所以基本上我是寻找来自服务器的任何事件,表明它已重新启动并运行?或者 netty 中自动处理这种重试机制的任何东西,希望现在对你有意义

标签: java sockets tcp netty


【解决方案1】:

您可以将DisconnectionHandler 作为客户端管道上的第一件事,通过立即尝试重新连接或安排重新连接任务来对channelInactive 做出反应。

例如,

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 的示例。

【讨论】:

  • 谢谢 Leo,这很有意义,你知道 netty 中是否有任何底层功能可以为我提供相同的功能,任何连接设置选项?
  • 我不知道。我会想到 ChannelPool (netty.io/4.0/api/index.html?io/netty/channel/pool/…) 实现中的一些东西,但似乎并非如此。
猜你喜欢
  • 1970-01-01
  • 2019-06-06
  • 2013-03-28
  • 2017-03-07
  • 2016-09-25
  • 2019-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多