What is a broken line reconnect

Disconnection reconnection refers to the service interruption caused by a network fault. The client needs to reconnect to the server. Under what circumstances will the service be disconnected? A common problem is that the client cannot interact with the server due to intermittent network conditions. For example, a power failure in the equipment room will also lead to service downtime. So in Netty service disconnection reconnection is very necessary to do a process;

2 Procedure for reconnecting a Netty cable

When does netty need to disconnect and reconnect?

When the Netty service is just started, the network needs to be disconnected and reconnected. In this case, the network needs to be disconnected and reconnected to ensure the normal running of the service. Secondly, when a network fault occurs during the operation of the service, it is necessary to disconnect and reconnect, so as to ensure that the service can be recovered immediately even after the downtime. Therefore, two steps are required for netty disconnection and reconnection.

The client is disconnected and reconnected

The Netty server does not need to be disconnected and reconnected. If the server service is down, you can only restart the service. So today we are studying the client disconnection reconnection;

3.1 Disconnection and reconnection during service startup

First we need to write a listener that implements the operationComplete method of the ChannelFutureListener interface. Here we use constructor injection to get the nettyClient instance. When a load listener is started after the client connection operation is complete, we use the result of channelFuture.isSuccess() to determine whether the client connection was successfully started. If not, start a new thread for reconnection to ensure successful client connection.

@Slf4j
public class ConnectionListener implements ChannelFutureListener {
    private NettyClient nettyClient;
    public ConnectionListener(NettyClient nettyClient) {
        this.nettyClient = nettyClient;
    }
    @Override
    public void operationComplete(ChannelFuture channelFuture) throws Exception {
        if(! channelFuture.isSuccess()) { log.warn("------------- Client reconnect -----------------");
            final EventLoop loop = channelFuture.channel().eventLoop();
            loop.schedule(new Runnable() {
                @SneakyThrows
                @Override
                public void run(a) {
                    nettyClient.connect(8080."127.0.0.1"); }},1L, TimeUnit.SECONDS); }}}Copy the code

Here we just implement a listener, and we need to inject the listener into the client;

public void connect(int port, String host) {

        // Create a thread group
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        // Netty starts helper classes
        Bootstrap bootstrap = new Bootstrap();
        //
        bootstrap.group(nioEventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // Handle I/O events
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        // Reconnection
                        pipeline.addLast(new NettyClientHandler(newNettyClient())); }});// Asynchronous operation
        ChannelFuture connect = null;
        try {
            connect = bootstrap
                    .connect(host, port)
                    .addListener(new ConnectionListener(this))// If the connection fails during netty startup, the network will be disconnected and reconnected
                    .sync();
            // Close the client
            connect.channel()
                    .closeFuture()
                    .sync();
        } catch(InterruptedException e) { e.printStackTrace(); }}Copy the code

3.2 Service Interruption and Reconnection

We implement a channelInactive method in NettyClientHandler that will be triggered to restart a thread when the server is disconnected;

@Slf4j
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    private NettyClient nettyClient;


    public NettyClientHandler(NettyClient nettyClient) {
        this.nettyClient = nettyClient;
    }
	/ /...

    / * * *@AuthorLSC * <p> run time disconnection reconnection </p> *@Param [ctx]
     * @Return* /
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        final EventLoop eventLoop = ctx.channel().eventLoop();
        eventLoop.schedule(new Runnable() {
            @Override
            public void run(a) {
                System.out.println("22222222222222222");
                nettyClient.connect(8080."127.0.0.1"); }},1L, TimeUnit.SECONDS);
        super.channelInactive(ctx);
    }
	/ /...
}
Copy the code

Analog disconnection and reconnection

First we start the server and client, and the knowledge seeker code gets a reply message;

The server image looks like the following

The client image looks like this

If the server is stopped, the client is disconnected and reconnected

The image looks like this

The server is restarted and successfully reconnected

This set of tutorials

  • Netty introduction (1)
  • NettyTCP Sticky Packet Unpacking (2)
  • Netty Disconnection and Reconnection (3)
  • Netty Heartbeat Detection Mechanism (4)
  • Netty encoding and decoding (5)
  • The backlog may have been updated