springboot + netty
时间: 2025-07-24 15:15:37 浏览: 14
在 Spring Boot 项目中集成 Netty,可以按照以下步骤进行配置和开发。Netty 是一个高性能的网络通信框架,适用于高并发、实时通信、自定义协议等场景[^2]。
### 添加 Maven 依赖
首先,在 `pom.xml` 文件中添加 Netty 的依赖项。如果需要 WebSocket 支持,也可以引入相关的依赖[^3]。
```xml
<!-- Netty 核心依赖 -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.68.Final</version>
</dependency>
<!-- WebSocket 支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- 可选:Netty WebSocket Spring Boot Starter -->
<dependency>
<groupId>org.yeauty</groupId>
<artifactId>netty-websocket-spring-boot-starter</artifactId>
<version>0.7.6</version>
</dependency>
```
### 创建 Netty 服务器配置类
接下来,创建一个 Netty 服务器类,用于启动 TCP 或 WebSocket 服务。以下是一个简单的 TCP 服务器实现:
```java
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;
import org.springframework.stereotype.Component;
@Component
public class NettyServer {
private final int port = 8080;
public void start() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new StringEncoder());
ch.pipeline().addLast(new NettyServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture future = bootstrap.bind(port).sync();
System.out.println("Netty 服务器启动成功,端口:" + port);
future.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
```
### 创建 Netty 服务器处理器
创建一个 `NettyServerHandler` 类,继承 `SimpleChannelInboundHandler`,用于处理客户端发送的消息:
```java
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
System.out.println("收到客户端消息:" + msg);
ctx.writeAndFlush("服务器收到消息:" + msg);
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println("客户端连接:" + ctx.channel().remoteAddress());
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
System.out.println("客户端断开连接:" + ctx.channel().remoteAddress());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
```
### 在 Spring Boot 启动类中启动 Netty 服务器
在 Spring Boot 启动类中通过 `CommandLineRunner` 接口来启动 Netty 服务器:
```java
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner startNettyServer(NettyServer nettyServer) {
return args -> {
nettyServer.start();
};
}
}
```
### 配置 WebSocket(可选)
如果需要支持 WebSocket,可以在 `application.properties` 中添加相关配置:
```properties
# WebSocket 配置
server.port=8080
```
同时,可以创建一个 WebSocket 服务器处理器:
```java
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
System.out.println("收到 WebSocket 消息:" + msg.text());
ctx.writeAndFlush(new TextWebSocketFrame("服务器收到消息:" + msg.text()));
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
System.out.println("客户端连接:" + ctx.channel().id().asShortText());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
System.out.println("客户端断开连接:" + ctx.channel().id().asShortText());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
```
### 总结
通过上述步骤,你可以在 Spring Boot 项目中成功集成 Netty,支持 TCP 和 WebSocket 协议的数据通信。这种方式适用于需要高性能、高并发、实时通信的场景。
---
阅读全文
相关推荐



















