2016-04-04 7 views
1

netty NIOを使用してTCP接続を確立するシナリオがありますが、サーバーがダウンしたときに、 可用性リスナーをサーバーに接続する方法はありますか?Nettyで切断された後に自動的にTCPサーバーに接続する方法

+0

興味深い質問ですが、可用性を得るためにサーバーにpingを実行することは可能でしょうか – HCarrasko

+0

しかし、その場合は、サーバーの可用性をチェックするのに忙しいスレッドを1つ保持する必要があります。 – Kaku

+0

ハンドラでChannelInactiveメソッドを使用してみてください – Ferrybig

答えて

2

は、すぐに再接続または再接続タスクのスケジューリングを試みることによってchannelInactiveで反応するクライアントパイプラインの最初のものとして持つことができます。 Exponential Backoff library例はこちら

public class ReconnectionTask extends 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. 
    } 
} 

チェック:例えば

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

はこのようなものになるだろう。

+0

ありがとう、それは理にかなっています。 – Kaku

+0

それはわかりません。私はChannelPool(http://netty.io/4.0/api/index.html?io/netty/channel/pool/package-summary.html)実装の中で何かを考えていますが、場合。 –

関連する問題