SpringBoot整合Netty的流程步骤

 更新时间:2023年09月20日 11:23:48   作者:fking86  
Netty是一个基于Java的开源网络应用框架,它提供了高性能、异步事件驱动的网络编程能力,Netty旨在帮助开发者构建高性能、高可靠性的网络应用程序,本文给大家详细介绍了SpringBoot整合Netty的流程步骤,需要的朋友可以参考下

简介

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

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

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

实例

版本依赖

JDK17

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();
        }

测试

先启动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

以上就是SpringBoot整合Netty的流程步骤的详细内容,更多关于SpringBoot整合Netty的资料请关注脚本之家其它相关文章!

相关文章

  • Java实现超市会员管理系统

    Java实现超市会员管理系统

    这篇文章主要为大家详细介绍了Java实现超市会员管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • Spring和Hibernate的整合操作示例

    Spring和Hibernate的整合操作示例

    这篇文章主要介绍了Spring和Hibernate的整合操作,结合实例形式详细分析了Spring和Hibernate的整合具体步骤、实现方法及相关操作注意事项,需要的朋友可以参考下
    2020-01-01
  • springmvc图片上传及json数据转换过程详解

    springmvc图片上传及json数据转换过程详解

    这篇文章主要介绍了springmvc图片上传及json数据转换过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • Java编程swing组件JLabel详解以及使用示例

    Java编程swing组件JLabel详解以及使用示例

    这篇文章主要介绍了Java编程swing组件JLabel详解以及使用示例,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • 高吞吐、线程安全的LRU缓存详解

    高吞吐、线程安全的LRU缓存详解

    这篇文章主要介绍了高吞吐、线程安全的LRU缓存详解,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下
    2018-02-02
  • 浅谈Java垃圾回收机制

    浅谈Java垃圾回收机制

    Java 中,程序员不需要关心所有不再使用的对象。垃圾回收机制自动销毁这些对象。垃圾回收机制是守护线程的最佳示例,因为它始终在后台运行。垃圾回收机制的主要目标是通过销毁无法访问的对象来释放堆内存。下面我们就来详细介绍吧
    2021-09-09
  • SpringBoot拦截器的使用介绍

    SpringBoot拦截器的使用介绍

    大家好,本篇文章主要讲的是SpringBoot拦截器的使用介绍,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下
    2022-01-01
  • Spring Boot项目抵御XSS攻击实战过程

    Spring Boot项目抵御XSS攻击实战过程

    XSS攻击又称跨站脚本攻击,通常指利用网页开发时留下的漏洞,通过巧妙的方法注入恶意指令代码到网页,使用户加载并执行攻击者恶意制造的网页程序,下面这篇文章主要给大家介绍了关于Spring Boot项目抵御XSS攻击的相关资料,需要的朋友可以参考下
    2022-11-11
  • Idea中导入新模块无法被识别的问题

    Idea中导入新模块无法被识别的问题

    这篇文章主要介绍了Idea中导入新模块无法被识别的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • java使用hashMap缓存保存数据的方法

    java使用hashMap缓存保存数据的方法

    这篇文章主要介绍了java使用hashMap缓存保存数据的方法,结合实例形式简单分析了java基于hashmap读写缓存数据的相关操作技巧,需要的朋友可以参考下
    2016-08-08

最新评论