在Springboot项目中,启动Netty服务器有两种方式:
(1)通过实现CommandLineRunner的方式;
(2)把Netty交给Spring容器来管理。
本文先介绍第一种,先对前面创建的Netty服务器稍微改造一下
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
/**
* @author: shensh
* @Desc:
* @create: 2025-09-24 11:03
**/
@Slf4j
public class NettyServer {
private NioEventLoopGroup bossGroup;
private NioEventLoopGroup workerGroup;
private Channel channel;
private int port;
public NettyServer(int port) {
this.port = port;
}
/**
* 启动Netty服务器
*/
public void start() {

最低0.47元/天 解锁文章
1422

被折叠的 条评论
为什么被折叠?



