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}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM