SoFunction
Updated on 2025-04-11

Springboot integrates netty to achieve heartbeat detection and automatic reconnection

1. Introduce dependencies

existAdd Netty and Spring Boot related dependencies to  .

<dependencies>
    <!-- Spring Boot Starter -->
    <dependency>
        <groupId></groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    
    <!-- Netty Dependency -->
    <dependency>
        <groupId></groupId>
        <artifactId>netty-all</artifactId>
        <version>4.1.</version>
    </dependency>
    
    <!-- Other related dependencies -->
</dependencies>

2. Configure Netty server

Create a Netty server startup class and configure the heartbeat detection mechanism.

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

@Component
public class NettyServer implements CommandLineRunner {

    private final int port = 8080;

    @Override
    public void run(String... args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            (bossGroup, workerGroup)
             .channel()
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ().addLast(new IdleStateHandler(5, 7, 10, ));
                     ().addLast(new HeartbeatHandler());
                 }
             })
             .option(ChannelOption.SO_BACKLOG, 128)
             .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = (port).sync();
            ().closeFuture().sync();
        } finally {
            ();
            ();
        }
    }
}

3. Implement the heartbeat detection processor

Create aHeartbeatHandlerClass-processing heartbeat detection.

import ;
import ;
import ;
import ;

public class HeartbeatHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (() == IdleState.READER_IDLE) {
                ("Reading Idle");
                // Close the connection                ();
            } else if (() == IdleState.WRITER_IDLE) {
                ("Writing free");
            } else if (() == IdleState.ALL_IDLE) {
                ("Read and write free");
                // Send heartbeat packet                ("ping\n");
            }
        } else {
            (ctx, evt);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ();
        ();
    }
}

4. Configure Netty Client

Create a Netty client startup class to implement automatic reconnection and heartbeat detection.

import ;
import .*;
import ;
import ;
import ;
import ;

import ;

@Component
public class NettyClient {

    private final String host = "localhost";
    private final int port = 8080;
    private final int MAX_RETRY = 5;
    private int retry = 0;

    public void start() {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            (group)
             .channel()
             .option(ChannelOption.SO_KEEPALIVE, true)
             .handler(new ChannelInitializer&lt;SocketChannel&gt;() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ().addLast(new IdleStateHandler(0, 4, 0, ));
                     ().addLast(new ClientHeartbeatHandler());
                 }
             });

            connect(b);
        } catch (Exception e) {
            ();
        }
    }

    private void connect(Bootstrap b) {
        (host, port).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (()) {
                    ("Connecting to the server successfully");
                } else {
                    ("Connecting to the server failed, try to reconnect");
                    retry++;
                    if (retry &lt; MAX_RETRY) {
                        ().eventLoop().schedule(() -&gt; connect(b), 2 &lt;&lt; retry, );
                    } else {
                        ("The number of reconnection failures reaches the maximum, the connection is abandoned");
                    }
                }
            }
        });
    }
}

5. Implement client heartbeat processor

Create aClientHeartbeatHandlerClass processing heartbeat package.

import ;
import ;
import ;
import ;

public class ClientHeartbeatHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (() == IdleState.WRITER_IDLE) {
                ("Send Heartbeat Package");
                ("ping\n");
            }
        } else {
            (ctx, evt);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ("Disconnect, try to reconnect");
        // Implement reconnection logic here        // For example: ().eventLoop().schedule(() -> connect(), 5, );    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ();
        ();
    }
}

6. Launch the Spring Boot app

Start the Netty server and client in the main class of Spring Boot.

import ;
import ;
import ;

import ;

@SpringBootApplication
public class NettySpringBootApplication {

    @Autowired
    private NettyServer nettyServer;

    @Autowired
    private NettyClient nettyClient;

    public static void main(String[] args) {
        (, args);
    }

    @PostConstruct
    public void startNetty() {
        new Thread(() -> {
            try {
                ();
            } catch (Exception e) {
                ();
            }
        }).start();

        new Thread(() -> ()).start();
    }
}

Summary of key points

  • Dependency introduction: Make sure that the necessary dependencies for Spring Boot and Netty are introduced.
  • Netty Server Configuration:useServerBootstrapConfigure the server side, including heartbeat detection processing.
  • Netty Client Configuration:useBootstrapConfigure the client to realize automatic reconnection and heartbeat detection.
  • Heartbeat processor: Implement the heartbeat detection processor on the server side and the client side respectively to handle the heartbeat packet and connection timeout.
  • Spring Boot Integration: Start the Netty server and client when the Spring Boot application starts.

This is the article about springboot integrating netty to achieve heartbeat detection and automatic reconnection. For more related springboot heartbeat detection and automatic reconnection, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!