Netty断线重连

时间:2022-05-04
本文章向大家介绍Netty断线重连,主要内容包括Netty断线重连、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

Netty断线重连

最近使用Netty开发一个中转服务,需要一直保持与Server端的连接,网络中断后需要可以自动重连,查询官网资料,实现方案很简单,核心思想是在channelUnregistered钩子函数里执行重连。

创建连接

需要把configureBootstrap重构为一个函数,方便后续复用

 EventLoopGroup group = new NioEventLoopGroup(); 
    private volatile Bootstrap bootstrap; 
 
    public void init(String host, int port) throws RobotException { 
        this.serverIp  = host; 
        this.serverPort = port; 
        try { 
            // 创建并初始化 Netty 客户端 Bootstrap 对象 
            bootstrap = configureBootstrap(new Bootstrap(),group); 
            bootstrap.option(ChannelOption.TCP_NODELAY, true); 
            doConnect(bootstrap); 
        } 
        catch(Exception ex){ 
            ex.printStackTrace(); 
            throw new RobotException("connect remote control server error!",ex.getCause()); 
        } 
    } 
 
    Bootstrap configureBootstrap(Bootstrap b, EventLoopGroup g) { 
        b.group(g).channel(NioSocketChannel.class) 
                .remoteAddress(serverIp, serverPort) 
                .handler(new ChannelInitializer<SocketChannel>() { 
                    @Override 
                    public void initChannel(SocketChannel channel) throws Exception { 
                        ChannelPipeline pipeline = channel.pipeline(); 
                        // 编解码器 
                        pipeline.addLast(protoCodec); 
                        // 请求处理 
                        pipeline.addLast(RobotClient.this); 
                    } 
                }); 
 
        return b; 
    } 
 
    void doConnect(Bootstrap b) { 
        try { 
 
            ChannelFuture future = b.connect(); 
            future.addListener(new ChannelFutureListener() { 
                @Override 
                public void operationComplete(ChannelFuture future) throws Exception { 
                    if (future.isSuccess()) { 
                        System.out.println("Started Tcp Client: " + serverIp); 
                    } else { 
                        System.out.println("Started Tcp Client Failed: "); 
                    } 
                    if (future.cause() != null) { 
                        future.cause().printStackTrace(); 
                    } 
 
                } 
            }); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    }

断线重连

来看断线重连的关键代码:

@ChannelHandler.Sharable 
public class RobotClient extends SimpleChannelInboundHandler<RobotProto>  { 
    @Override 
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { 
        // 状态重置 
        isConnected = false; 
        this.serverStatus = -1; 
 
        final EventLoop loop = ctx.channel().eventLoop(); 
        loop.schedule(new Runnable() { 
            @Override 
            public void run() { 
                doConnect(configureBootstrap(new Bootstrap(), loop)); 
            } 
        }, 1, TimeUnit.SECONDS); 
    } 
}