Netty client uses an exponential backoff mechanism to achieve reconnection

Index retreated

Can be understood as the index level prior to each reconnection fails, put the reconnection time is set. Example, 2 seconds, 4 seconds, 8 seconds ......

Amazon AWS on the exponential backoff introduction of two articles

Netty client using exponential backoff mode reconnection

The client connecting to the server, call the connect method of Bootstrap:

bootstrap.connect(host, port)

This method will return ChannelFuture, ChannelFuture realized netty's Future , 而Future Inherited from java.util.concurrent.Future This is the result of the asynchronous operation, it is thus connect an asynchronous method. We can add the listener by calling addListener, monitor whether the connection is successful.

  • As used herein GenericFutureListener, ChannelFutureListener can also use this interface.
   /**
     * 连接和重连机制,实现了指数退避重连
     * @param bootstrap
     * @param host
     * @param port
     * @param retry
     */
    private static void connect(Bootstrap bootstrap, String host, int port, int retry) {

        bootstrap.connect(host, port).addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                if (future.isSuccess()) {
                    LOGGER.info("连接服务器成功!");
                } else if (retry == 0) {
                    LOGGER.error("重连次数已用完,放弃连接!");
                } else {
                    // 第几次重连
                    int order = (MAX_RETRY - retry) + 1;
                    // 本次重连的间隔
                    int delay = 1 << order;
                    LOGGER.error(new Date() + ": 连接失败,第" + order + "次重连……");

                    bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retry - 1), delay, TimeUnit.SECONDS);
                }
            }
        });
    }
  • () Determines whether the connection is successful through future.isSuccess.
  • int delay = 1 << order; fast reconnect time interval is calculated by left shift operations.
  • bootstrap.config (). group (). schedule () implement timed task logic.

reference

US Mission Flash client startup process

Guess you like

Origin www.cnblogs.com/monkjavaer/p/11261136.html