0


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

🌵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

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

🔔写在最后

如果大家对相关文章感兴趣,可以关注公众号"架构殿堂",会持续更新AIGC,java基础面试题, netty, spring boot, spring cloud等系列文章,一系列干货随时送达!
标签: spring boot 后端 java

本文转载自: https://blog.csdn.net/jinxinxin1314/article/details/132862214
版权归原作者 fking86 所有, 如有侵权,请联系我们删除。

“SpringBoot整合Netty”的评论:

还没有评论