JAVA:Spring Boot 集成 Netty 异步事件驱动

admin
0
2026-12-02

1、简述

Netty 是一款异步事件驱动的网络应用框架,支持快速开发高性能、高可用的网络服务器和客户端。它被广泛应用于分布式系统中,比如消息中间件、RPC 框架等。

样例代码: https://gitee.com/lhdxhl/springboot-example.git

image-xxfp.png


2、什么是 Netty?

Netty 是基于 Java 的网络编程框架,它屏蔽了底层复杂的网络通信细节,提供了简单易用的 API。Netty 的核心特点包括:

🔥 高性能: 基于 NIO(非阻塞 IO)模型,支持多路复用和高效的数据传输。

🔥 事件驱动: 采用事件驱动的架构,便于扩展和自定义。

🔥 跨平台: 由于基于 Java 开发,Netty 可运行在任何支持 JVM 的平台上。

🔥 灵活: 提供丰富的编解码器、处理器,可以满足各种协议的开发需求。

Netty 的核心组件

🔥 Channel: 网络通信的基本抽象,代表一个连接。

🔥 EventLoop: 处理 Channel 的 IO 操作和事件。

🔥 ChannelHandler: 用于处理 Channel 中的各种事件。

🔥 Pipeline: 事件处理的流水线,包含多个 ChannelHandler。

🔥 Bootstrap: 启动类,用于配置和启动 Netty 服务。

image-0o2l.png


3、实践样例

以下是一个完整的 Netty 服务端和客户端通信样例。

3.1 Netty 引用

在使用 Netty 之前,需要添加其依赖。以下是 Netty 的 Maven 依赖:

<dependency>
	<groupId>io.netty</groupId>
	<artifactId>netty-all</artifactId>
	<version>4.1.36.Final</version>
</dependency>

3.2 服务端代码

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
        // 创建两个线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 服务端启动类
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringDecoder()); // 解码器
                        pipeline.addLast(new StringEncoder()); // 编码器
                        pipeline.addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) {
                                System.out.println("接收到客户端消息:" + msg);
                                ctx.writeAndFlush("服务端已收到:" + msg);
                            }
                        });
                    }
                });

            System.out.println("Netty 服务器启动中...");
            ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

3.3 客户端代码

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            // 客户端启动类
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringDecoder()); // 解码器
                        pipeline.addLast(new StringEncoder()); // 编码器
                        pipeline.addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) {
                                System.out.println("接收到服务端消息:" + msg);
                            }
                        });
                    }
                });

            System.out.println("Netty 客户端启动中...");
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8080).sync();
            Channel channel = channelFuture.channel();
            channel.writeAndFlush("你好,Netty 服务端!");
            channel.closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}

样例说明

🔥 服务端: 使用 ServerBootstrap 启动服务,监听 8080 端口,并处理来自客户端的消息。

🔥 客户端: 使用 Bootstrap 连接到服务端,发送消息并接收响应。

🔥 编解码器: 使用 StringDecoder 和 StringEncoder 处理字符串的编码与解码。


4、Netty 的典型应用场景

🔥 IM 即时通讯: 支持高并发和低延迟的通信需求。

🔥 文件传输: 提供高效的数据流传输能力。

🔥 消息队列: 例如 RocketMQ 就基于 Netty 实现了网络通信层。

🔥 RPC 框架: Dubbo 和 gRPC 的通信底层也可以使用 Netty。

5、总结

Netty 提供了高效、灵活的网络编程支持。在实际开发中,可以根据具体需求,扩展 Netty 的处理器,构建适合自己业务场景的网络应用。

如果您对 Netty 的使用有其他问题,欢迎留言交流!

动物装饰