What's the best way to reconnect after connection closed in Netty

后端 未结 3 1603
青春惊慌失措
青春惊慌失措 2021-02-01 10:11

Simple scenario:

  1. A lower level class A that extends SimpleChannelUpstreamHandler. This class is the workhorse to send the message and received the response.
3条回答
  •  别那么骄傲
    2021-02-01 11:03

    Channel.closeFuture() returns a ChannelFuture that will notify you when the channel is closed. You can add a ChannelFutureListener to the future in B so that you can make another connection attempt there.

    You probably want to repeat this until the connection attempt succeeds finally:

    private void doConnect() {
        Bootstrap b = ...;
        b.connect().addListener((ChannelFuture f) -> {
            if (!f.isSuccess()) {
                long nextRetryDelay = nextRetryDelay(...);
                f.channel().eventLoop().schedule(nextRetryDelay, ..., () -> {
                    doConnect();
                }); // or you can give up at some point by just doing nothing.
            }
        });
    }
    

提交回复
热议问题