SpringBoot整合Netty

这篇具有很好参考价值的文章主要介绍了SpringBoot整合Netty。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


springboot整合netty框架,SpringBoot,netty,spring boot,后端,java

简介

Netty是一个基于Java的开源网络应用框架,它提供了高性能、异步事件驱动的网络编程能力。Netty旨在帮助开发者构建高性能、高可靠性的网络应用程序。

Netty提供了简洁的API和丰富的功能,可以轻松处理各种网络通信协议,如TCP、UDP、WebSocket等。它的设计理念是基于事件驱动和回调机制,而不是传统的线程模型,这使得它可以实现高并发、低延迟的网络通信。

通过使用Netty,开发者可以方便地处理复杂的网络通信逻辑,例如请求-响应模式、长连接、心跳检测等。Netty提供了灵活的编解码器和处理器,可以对网络数据进行高效的编解码和处理。同时,Netty还提供了可靠的错误处理机制和事件机制,方便开发者进行异常处理和扩展。


Netty特点

springboot整合netty框架,SpringBoot,netty,spring boot,后端,java

  1. 高性能

    Netty采用了基于事件驱动的异步模型,通过使用非阻塞I/O操作和多线程处理请求,实现了高性能的网络通信。

  2. 高可靠性

    Netty提供了一套强大的错误处理机制,包括异常处理、断线重连、心跳检测等,可以有效地处理网络中的各种异常情况,提高应用程序的可靠性。

  3. 高可扩展性

    Netty的设计模式和组件化架构使得它非常易于扩展和定制。开发人员可以根据自己的需求,选择合适的组件和模块,构建出符合自己业务需求的网络应用程序。

  4. 支持多种协议

    Netty支持多种常用的网络协议,包括HTTP、WebSocket、TCP、UDP等,可以满足不同场景下的网络通信需求。

实例

版本依赖
模块 版本号
JDK 17
SpringBoot 3.1.0
Netty 4.1.90.Final
引入依赖
<modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>springboot-netty</artifactId>
    <name>${project.artifactId}</name>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <java.version>17</java.version>
        <maven.version>17</maven.version>
    </properties>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--   引入Netty依赖     -->
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.90.Final</version>
        </dependency>
    </dependencies>
EchoServer
// 创建Server端
        EventLoopGroup workGroup = new NioEventLoopGroup();
        final EchoServerHandler serverHandler = new EchoServerHandler();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(workGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new LoggingHandler(LogLevel.INFO));
                            p.addLast(serverHandler);
                        }
                    });
            // 绑定端口
            ChannelFuture f = b.bind(8088).sync();
            // 等待连接关闭
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 关闭所有线程
            workGroup.shutdownGracefully();
        }
EchoServerHandler
@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {


    /**
     * 读取
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ctx.write(msg);
    }

    /**
     * 读取完毕时
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    /**
     * 抓住异常
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
EchoClient
EventLoopGroup group = new NioEventLoopGroup();
        EchoClientHandler clientHandler = new EchoClientHandler();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new LoggingHandler(LogLevel.INFO));
                            p.addLast(clientHandler);
                        }
                    });
            // 连接server端
            ChannelFuture cf = b.connect("127.0.0.1", 8088).sync();
            // 等待连接关闭
            cf.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
EchoClientHandler
@Sharable
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

    private final ByteBuf firstMsg;

    public EchoClientHandler() {
        firstMsg = Unpooled.wrappedBuffer("Hello Netty Socket Codeing".getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 通道活跃时
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 第一次传输
        ctx.writeAndFlush(firstMsg);
    }

    /**
     * 读取数据时
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ctx.write(msg);
    }

    /**
     * 读取完毕时
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // 延迟3秒
        TimeUnit.SECONDS.sleep(3);
        ctx.flush();
    }

    /**
     * 捕获到异常时
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
测试

先启动EchoServer,再启动EchoClient

18:36:39.872 [nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler -- [id: 0xe21b38be, L:/127.0.0.1:54127 - R:/127.0.0.1:8088] WRITE: 26B
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 48 65 6c 6c 6f 20 4e 65 74 74 79 20 53 6f 63 6b |Hello Netty Sock|
|00000010| 65 74 20 43 6f 64 65 69 6e 67                   |et Codeing      |
+--------+-------------------------------------------------+----------------+
18:36:39.872 [nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler -- [id: 0xe21b38be, L:/127.0.0.1:54127 - R:/127.0.0.1:8088] READ COMPLETE
18:36:42.882 [nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler -- [id: 0xe21b38be, L:/127.0.0.1:54127 - R:/127.0.0.1:8088] FLUSH
18:36:42.885 [nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler -- [id: 0xe21b38be, L:/127.0.0.1:54127 - R:/127.0.0.1:8088] READ: 26B
HttpServer (HTTP服务)
// 主从模式
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();

try {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    // HTTP 模式
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new HttpServerCodec());
                    p.addLast(new HttpServerExpectContinueHandler());
                    p.addLast(new HttpServerHandler());
                }
            });
    ChannelFuture ch = b.bind(8089).sync();

    System.out.println("Open Http Server : http://127.0.0.1:8089");
    ch.channel().closeFuture().sync();

} catch (Exception ex) {
    ex.printStackTrace();
} finally {
    workerGroup.shutdownGracefully();
    bossGroup.shutdownGracefully();
}
测试Http

访问链接:http://127.0.0.1:8089

hello netty http coding

总结

本文介绍了Spring Boot和Netty的基本概念和特点。然后,它详细解释了如何在Spring Boot项目中添加Netty依赖项,并配置Netty服务器。接下来,文章介绍了如何创建一个简单的Netty处理器,用于处理传入的网络请求。然后,它展示了如何在Spring Boot应用程序中使用这个Netty处理器。

这篇文章提供了一个清晰的指南,帮助读者了解如何在Spring Boot应用程序中集成和使用Netty。它涵盖了从添加依赖项到配置服务器,创建处理器,处理异常和错误,以及处理并发请求的方方面面。对于那些希望在Spring Boot项目中使用Netty的开发人员来说,这篇文章是一个很好的参考资料。


源码下载

​如果需要完整源码请关注公众号"架构殿堂" ,回复 "SpringBoot+Netty"即可获得


写在最后

感谢您的支持和鼓励! 😊🙏

如果大家对相关文章感兴趣,可以关注公众号"架构殿堂",会持续更新AIGC,系统架构, 分布式, java, GO, python, 游戏相关 等系列文章,一系列干货随时送达!

springboot整合netty框架,SpringBoot,netty,spring boot,后端,java文章来源地址https://www.toymoban.com/news/detail-716762.html

到了这里,关于SpringBoot整合Netty的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Spring Boot】SpringBoot 优雅整合Swagger Api 自动生成文档

    Swagger 是一套 RESTful API 文档生成工具,可以方便地生成 API 文档并提供 API 调试页面。 而 Spring Boot 是一款非常优秀的 Java Web 开发框架,它可以非常方便地构建 Web 应用程序。 在本文中,我们将介绍如何使用 Swagger 以及如何在 Spring Boot 中整合 Swagger 。 首先,在 pom.xml 文件中添

    2023年04月22日
    浏览(34)
  • SpringBoot + Vue前后端分离项目实战 || 三:Spring Boot后端与Vue前端连接

    系列文章: SpringBoot + Vue前后端分离项目实战 || 一:Vue前端设计 SpringBoot + Vue前后端分离项目实战 || 二:Spring Boot后端与数据库连接 SpringBoot + Vue前后端分离项目实战 || 三:Spring Boot后端与Vue前端连接 SpringBoot + Vue前后端分离项目实战 || 四:用户管理功能实现 SpringBoot + Vue前后

    2024年02月12日
    浏览(56)
  • SpringBoot + Vue前后端分离项目实战 || 二:Spring Boot后端与数据库连接

    系列文章: SpringBoot + Vue前后端分离项目实战 || 一:Vue前端设计 SpringBoot + Vue前后端分离项目实战 || 二:Spring Boot后端与数据库连接 SpringBoot + Vue前后端分离项目实战 || 三:Spring Boot后端与Vue前端连接 SpringBoot + Vue前后端分离项目实战 || 四:用户管理功能实现 SpringBoot + Vue前后

    2024年02月11日
    浏览(50)
  • SpringBoot整合Netty

    简介 Netty是一个基于Java的开源网络应用框架,它提供了高性能、异步事件驱动的网络编程能力。Netty旨在帮助开发者构建高性能、高可靠性的网络应用程序。 Netty提供了简洁的API和丰富的功能,可以轻松处理各种网络通信协议,如TCP、UDP、WebSocket等。它的设计理念是基于事件

    2024年02月08日
    浏览(24)
  • Netty系列(一):Springboot整合Netty,自定义协议实现

    Netty是由JBOSS提供的一个java开源框架,现为 Github上的独立项目。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。 也就是说,Netty 是一个基于NIO的客户、服务器端的编程框架,使用Netty 可以确保你快速和简单

    2023年04月25日
    浏览(45)
  • springboot整合netty的正确姿势

    近期做一些物联网方面项目,使用到了tcp协议,之前公司做过socket短连接,网上找了一个简单的demo,很早便学习到nio方面知识,学习了《netty从入门到精通》这本书,同时也根据网上视频做了几个demo,但学习不太深入,刚好物联网项目,就直接使用netty,前期直接使用这个框

    2024年02月05日
    浏览(30)
  • Springboot整合Netty,自定义协议实现

    新建springboot项目,并在项目以来中导入netty包,用fastjson包处理jsonStr。 创建netty相关配置信息文件 yml配置文件—— application.yml netty配置实体类—— NettyProperties 与yml配置文件绑定 通过 @ConfigurationProperties(prefix = \\\"netty\\\") 注解读取配置文件中的netty配置,通过反射注入值,需要在

    2024年02月06日
    浏览(28)
  • SpringBoot整合Netty+Websocket实现消息推送

           Netty是一个高性能、异步事件驱动的网络应用框架,用于快速开发可维护的高性能协议服务器和客户端。以下是Netty的主要优势: 高性能 :Netty基于NIO(非阻塞IO)模型,采用事件驱动的设计,具有高性能的特点。它通过零拷贝技术、内存池化技术等手段,进一步提高

    2024年01月20日
    浏览(33)
  • Springboot整合Netty实现RPC服务器

    try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, worker) .childHandler(new ChannelInitializer() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new IdleStateHandler(0, 0, 60)); pipeline.addLast(new JsonDecoder()); pipeline.addLast(new JsonEnco

    2024年04月09日
    浏览(33)
  • 日常记录-SpringBoot整合netty-socketio

    这次整合借鉴了以下博主的智慧 websocket和socketio的区别 socket.io.js最简版单页HTML测试工具 Netty-SocketIO多路复用 springboot学习(四十三) springboot使用netty-socketio实现消息推送 SpringBoot集成SocketIO socketio的核心依赖就只有这个 我在启动类里面定义了启动或者关闭SocketIOServer springboot整合

    2024年02月10日
    浏览(34)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包