netty5客户端监测服务端断连后重连

  服务端挂了或者主动拒绝客户端的连接后,客户端不死心,每15秒重连试试,3次都不行就算了。修改下之前的客户端引导类(NettyClient,参见netty5心跳与业务消息分发实例),新增两个成员变量,在connect连接方法里的finally加入重连操作:

    private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    private AtomicInteger reconnetTimes = new AtomicInteger(0);

    public void connect(int port, String host) throws Exception {
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast(new NettyMessageDecoder());
                            channel.pipeline().addLast(new NettyMessageEncoder());
                            channel.pipeline().addLast(new ControlClientHandler());
                            channel.pipeline().addLast(new HeartBeatClientHandler());
//                            channel.pipeline().addLast(new NettyClientHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect(host, port).sync();
            future.channel().closeFuture().sync();
        } finally {

            group.shutdownGracefully();

            // 所有资源释放完成之后,清空资源,再次发起重连操作
            executorService.execute(new Runnable() {
                @Override
                public void run() {

                    // 重连3次均失败,关闭线程池
                    if (reconnetTimes.get() > 3) {
                        log.error("reconnect times > 3.");
                        executorService.shutdown();
                    }

                    // 每15秒重连一次
                    try {
                        TimeUnit.SECONDS.sleep(15);
                        try {
                            // 发起重连操作,连接成功后将阻塞
                            connect(port, "127.0.0.1");
                        } catch (Exception e) {
                            reconnetTimes.getAndIncrement();
                            log.error("client try to reconnect failed, error : {}", e.getMessage());
                        }
                    } catch (InterruptedException e) {
                        reconnetTimes.incrementAndGet();
                        log.error("client try to reconnect failed, error : {}", e.getMessage());
                    }

                }
            });
        }
    }

  不起服务端,我们只起客户端,输出如下:

Exception in thread "main" java.net.ConnectException: Connection refused: no further information: /127.0.0.1:9911
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
    at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:223)
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:276)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:531)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:471)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:385)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:351)
    at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
    at io.netty.util.internal.chmv8.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1412)
    at io.netty.util.internal.chmv8.ForkJoinTask.doExec(ForkJoinTask.java:280)
    at io.netty.util.internal.chmv8.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:877)
    at io.netty.util.internal.chmv8.ForkJoinPool.scan(ForkJoinPool.java:1706)
    at io.netty.util.internal.chmv8.ForkJoinPool.runWorker(ForkJoinPool.java:1661)
    at io.netty.util.internal.chmv8.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:126)
17:02:02.968 [pool-1-thread-1] ERROR com.wlf.netty.nettyclient.client.NettyClient - client try to reconnect failed, error : Connection refused: no further information: /127.0.0.1:9911
17:02:19.013 [pool-1-thread-1] ERROR com.wlf.netty.nettyclient.client.NettyClient - client try to reconnect failed, error : Connection refused: no further information: /127.0.0.1:9911
17:02:35.063 [pool-1-thread-1] ERROR com.wlf.netty.nettyclient.client.NettyClient - client try to reconnect failed, error : Connection refused: no further information: /127.0.0.1:9911
17:02:51.112 [pool-1-thread-1] ERROR com.wlf.netty.nettyclient.client.NettyClient - client try to reconnect failed, error : Connection refused: no further information: /127.0.0.1:9911
17:02:51.112 [pool-1-thread-1] ERROR com.wlf.netty.nettyclient.client.NettyClient - reconnect times > 3.
17:03:07.140 [pool-1-thread-1] ERROR com.wlf.netty.nettyclient.client.NettyClient - client try to reconnect failed, error : Task java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask@16c59706 rejected from java.util.concurrent.ScheduledThreadPoolExecutor@6fa6a4f0[Shutting down, pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 4]

Process finished with exit code 1

  如果3次重连过程中你把服务端起了,那么客户端就会连上去:

Exception in thread "main" java.net.ConnectException: Connection refused: no further information: /127.0.0.1:9911
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
    at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:223)
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:276)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:531)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:471)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:385)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:351)
    at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
    at io.netty.util.internal.chmv8.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1412)
    at io.netty.util.internal.chmv8.ForkJoinTask.doExec(ForkJoinTask.java:280)
    at io.netty.util.internal.chmv8.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:877)
    at io.netty.util.internal.chmv8.ForkJoinPool.scan(ForkJoinPool.java:1706)
    at io.netty.util.internal.chmv8.ForkJoinPool.runWorker(ForkJoinPool.java:1661)
    at io.netty.util.internal.chmv8.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:126)
17:06:40.171 [pool-1-thread-1] ERROR com.wlf.netty.nettyclient.client.NettyClient - client try to reconnect failed, error : Connection refused: no further information: /127.0.0.1:9911
17:06:56.219 [pool-1-thread-1] ERROR com.wlf.netty.nettyclient.client.NettyClient - client try to reconnect failed, error : Connection refused: no further information: /127.0.0.1:9911
17:07:11.297 [nioEventLoopGroup-4-0] DEBUG io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetectionLevel: simple
17:07:11.304 [nioEventLoopGroup-4-0] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.maxCapacity: 262144
17:07:11.366 [nioEventLoopGroup-4-0] INFO com.wlf.netty.nettyclient.handler.HeartBeatClientHandler - [client] control response is OK, header : Header{delimiter=-1410399999, length=8, type=0, reserved=0}. sid : 63, interval : 5000
17:07:16.412 [nioEventLoopGroup-4-0] INFO com.wlf.netty.nettyclient.handler.HeartBeatClientHandler - [client] Client send heart beat message to server : ----> NettyMessage{header=Header{delimiter=-1410399999, length=4, type=3, reserved=0}, data=[B@682470ef}
17:07:16.412 [nioEventLoopGroup-4-0] INFO com.wlf.netty.nettyclient.handler.HeartBeatClientHandler - [client] Client send business message to server : ----> NettyMessage{header=Header{delimiter=-1410399999, length=161800, type=1, reserved=0}, data=[B@41bd2db4}
原文地址:https://www.cnblogs.com/wuxun1997/p/11753579.html