最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot整合netty實現(xiàn)心跳檢測和自動重連

 更新時間:2024年11月21日 09:20:50   作者:如夜了我衣衫太薄便歸家靠路燈°  
本文主要介紹了Spring Boot中整合Netty實現(xiàn)心跳檢測和自動重連,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

1. 引入依賴

在 pom.xml 中添加 Netty 和 Spring Boot 相關依賴。

<dependencies>
    <!-- Spring Boot Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    
    <!-- Netty Dependency -->
    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-all</artifactId>
        <version>4.1.63.Final</version>
    </dependency>
    
    <!-- 其他相關依賴 -->
</dependencies>

2. 配置 Netty 服務端

創(chuàng)建一個 Netty 服務器啟動類,配置心跳檢測機制。

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@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();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(new IdleStateHandler(5, 7, 10, TimeUnit.SECONDS));
                     ch.pipeline().addLast(new HeartbeatHandler());
                 }
             })
             .option(ChannelOption.SO_BACKLOG, 128)
             .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}

3. 實現(xiàn)心跳檢測處理器

創(chuàng)建一個 HeartbeatHandler 類處理心跳檢測。

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleState;

public class HeartbeatHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                System.out.println("讀空閑");
                // 關閉連接
                ctx.close();
            } else if (event.state() == IdleState.WRITER_IDLE) {
                System.out.println("寫空閑");
            } else if (event.state() == IdleState.ALL_IDLE) {
                System.out.println("讀寫空閑");
                // 發(fā)送心跳包
                ctx.writeAndFlush("ping\n");
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

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

4. 配置 Netty 客戶端

創(chuàng)建一個 Netty 客戶端啟動類,實現(xiàn)自動重連和心跳檢測。

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@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();
            b.group(group)
             .channel(NioSocketChannel.class)
             .option(ChannelOption.SO_KEEPALIVE, true)
             .handler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS));
                     ch.pipeline().addLast(new ClientHeartbeatHandler());
                 }
             });

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

    private void connect(Bootstrap b) {
        b.connect(host, port).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    System.out.println("連接服務器成功");
                } else {
                    System.out.println("連接服務器失敗,嘗試重連");
                    retry++;
                    if (retry < MAX_RETRY) {
                        future.channel().eventLoop().schedule(() -> connect(b), 2 << retry, TimeUnit.SECONDS);
                    } else {
                        System.out.println("重連失敗次數(shù)達到最大,放棄連接");
                    }
                }
            }
        });
    }
}

5. 實現(xiàn)客戶端心跳處理器

創(chuàng)建一個 ClientHeartbeatHandler 類處理心跳包。

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleState;

public class ClientHeartbeatHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.WRITER_IDLE) {
                System.out.println("發(fā)送心跳包");
                ctx.writeAndFlush("ping\n");
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("連接斷開,嘗試重連");
        // 在這里實現(xiàn)重連邏輯
        // 比如: ctx.channel().eventLoop().schedule(() -> connect(), 5, TimeUnit.SECONDS);
    }

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

6. 啟動 Spring Boot 應用

在 Spring Boot 的主類中啟動 Netty 服務器和客戶端。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.PostConstruct;

@SpringBootApplication
public class NettySpringBootApplication {

    @Autowired
    private NettyServer nettyServer;

    @Autowired
    private NettyClient nettyClient;

    public static void main(String[] args) {
        SpringApplication.run(NettySpringBootApplication.class, args);
    }

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

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

關鍵點總結

  • 依賴引入:確保引入了 Spring Boot 和 Netty 的必要依賴。
  • Netty 服務器配置:使用 ServerBootstrap 配置服務器端,包括心跳檢測處理。
  • Netty 客戶端配置:使用 Bootstrap 配置客戶端,實現(xiàn)自動重連和心跳檢測。
  • 心跳處理器:在服務器端和客戶端分別實現(xiàn)心跳檢測處理器,處理心跳包和連接超時。
  • Spring Boot 集成:在 Spring Boot 應用啟動時啟動 Netty 服務器和客戶端。

到此這篇關于springboot整合netty實現(xiàn)心跳檢測和自動重連的文章就介紹到這了,更多相關springboot 心跳檢測和自動重連內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家! 

相關文章

  • java微信企業(yè)號開發(fā)之通訊錄

    java微信企業(yè)號開發(fā)之通訊錄

    這篇文章主要為大家詳細介紹了java微信企業(yè)號開發(fā)之通訊錄的相關資料,感興趣的小伙伴們可以參考一下
    2016-06-06
  • java.util.ArrayDeque類使用方法詳解

    java.util.ArrayDeque類使用方法詳解

    這篇文章主要介紹了java.util.ArrayDeque類使用方法,java.util.ArrayDeque類提供了可調整大小的陣列,并實現(xiàn)了Deque接口,感興趣的小伙伴們可以參考一下
    2016-03-03
  • NoHttpResponseException問題分析解決記錄

    NoHttpResponseException問題分析解決記錄

    這篇文章主要為大家介紹了NoHttpResponseException問題分析解決記錄,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-08-08
  • Java String創(chuàng)建對象實例解析

    Java String創(chuàng)建對象實例解析

    這篇文章主要介紹了Java String創(chuàng)建對象實例解析,分享了相關代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下
    2018-02-02
  • SpringBoot-RestTemplate如何實現(xiàn)調用第三方API

    SpringBoot-RestTemplate如何實現(xiàn)調用第三方API

    這篇文章主要介紹了SpringBoot-RestTemplate實現(xiàn)調用第三方API的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • Java透明窗體的設置方法

    Java透明窗體的設置方法

    在本文中我們給大家整理了關于Java透明窗體的設置方法以及需要注意的地方,需要的朋友們學習參考下。
    2019-03-03
  • 如何使用SpringSecurity保護程序安全

    如何使用SpringSecurity保護程序安全

    這篇文章主要介紹了如何使用SpringSecurity保護程序安全,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-09-09
  • 如何通過Java生成一個隨機數(shù)

    如何通過Java生成一個隨機數(shù)

    當我們需要在Java中生成隨機數(shù)時,可以借助JDK中提供的Random類來實現(xiàn),通過使用Random類,我們可以輕松地生成各種類型的隨機數(shù),下面我們就來看看如何利用Random類生成隨機數(shù)吧
    2023-09-09
  • Java實現(xiàn)和電腦玩剪刀石頭布游戲

    Java實現(xiàn)和電腦玩剪刀石頭布游戲

    這篇文章主要為大家詳細介紹了Java實現(xiàn)和電腦玩剪刀石頭布游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • Java基礎知識之I/O流和File類文件操作

    Java基礎知識之I/O流和File類文件操作

    眾所周知java語言提供給程序員非常多的包供編程時使用,方便又快捷,下面這篇文章主要給大家介紹了關于Java基礎知識之I/O流和File類文件操作的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-04-04

最新評論

云和县| 深圳市| 大宁县| 泰安市| 景谷| 峨眉山市| 封丘县| 平乐县| 九江市| 齐齐哈尔市| 玛多县| 疏勒县| 镇康县| 新邵县| 白山市| 安阳县| 乐至县| 凭祥市| 泾川县| 静安区| 吴川市| 宜黄县| 绵阳市| 高碑店市| 扬中市| 仁怀市| 庐江县| 黑河市| 邻水| 阳泉市| 大城县| 内乡县| 辛集市| 青田县| 潜山县| 张家界市| 枣庄市| 门头沟区| 综艺| 夏邑县| 柘城县|