启动时候服务端不在线

        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.group(eventLoopGroup);
        bootstrap.remoteAddress(host, port);
        bootstrap.handler(fidsClientChannelInit);
        ChannelFuture future = bootstrap.connect(host, port);
        future.addListener(reConnectListener);

ReConnectListener.java

package com.cares.fids.client.comm.listener;

import com.cares.fids.client.comm.FidsClient;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author wangcj
 * @desc
 * @date 2020/12/23 0:19
 **/
@Slf4j
@Component
public class ReConnectListener implements ChannelFutureListener {

    @Resource
    private FidsClient fidsClient;

    @Override
    public void operationComplete(ChannelFuture channelFuture) throws Exception {
        if (!channelFuture.isSuccess()) {
            final EventLoop loop = channelFuture.channel().eventLoop();
            loop.schedule(() -> {
                System.err.println("服务端链接不上,开始重连操作...");
                fidsClient.start();
            }, 1L, TimeUnit.SECONDS);
        } else {
            log.info("服务端链接成功...");
        }
    }
}

客户端运行中服务端掉线


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        final EventLoop eventLoop = ctx.channel().eventLoop();
        eventLoop.schedule(() -> fidsClient.start(), 1L, TimeUnit.SECONDS);
        super.channelInactive(ctx);
    }


JAVA      netty 断线重连

本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!