Springboot中启动netty的两种方式

在SpringBoot中启动Netty

方式1

  1. 设置一个ApplicationListener

    @Component
    public class NettyBooter implements ApplicationListener<ContextRefreshedEvent>{
    
    	@Override
    	public void onApplicationEvent(ContextRefreshedEvent event) {
    		if(event.getApplicationContext().getParent()==null) {
    			try {
    				NettyServer.getInstance().start();
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
    	}
    }
    
  2. NettyServer

    @Component
    public class NettyServer {
        private static class SingletonNettyServer{
            static final NettyServer instance = new NettyServer();
        }
    
        private EventLoopGroup mainGroup;
        private EventLoopGroup subGroup;
        private ServerBootstrap serverBootstrap;
        private ChannelFuture future;
    
        public static NettyServer getInstance() {
            return SingletonNettyServer.instance;
        }
    
        public NettyServer(){
            mainGroup = new NioEventLoopGroup();
            subGroup = new NioEventLoopGroup();
            serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(mainGroup, subGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new NettyServerInitializer());
        }
    
        public void start(){
            this.future = serverBootstrap.bind(9999);
            System.err.println("netty 服务启动成功");
        }
    }
    

方式2

使用注解@PostConstruct启动

参考文章

@Component大家都能熟悉了,就是把普通pojo实例化到spring容器中,相当于配置文件中的。泛指各种组件,比如类不属于@Controller或者@Service等时,就可以用该注解标注;

@PostConstruct这个注解是我第一次接触,在方法上加该注解会在项目启动的时候执行该方法,即spring容器初始化的时候执行,它与构造函数及@Autowired的执行顺序为:构造函数 >> @Autowired >> @PostConstruct,由此看来当我们想在生成对象时完成某些初始化操作,而偏偏这些初始化操作又依赖于注入的bean,那么就无法在构造函数中实现,为此可以使用@PostConstruct注解一个init方法来完成初始化,该方法会在bean注入完成后被自动调用。

@Component
public class NettyServer {
    private EventLoopGroup mainGroup;
    private EventLoopGroup subGroup;
    private ServerBootstrap serverBootstrap;
    private ChannelFuture future;

    public NettyServer(){
        mainGroup = new NioEventLoopGroup();
        subGroup = new NioEventLoopGroup();
        serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(mainGroup, subGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new NettyServerInitializer());
    }

    @PostConstruct
    public void start(){
        this.future = serverBootstrap.bind(9999);
        System.err.println("netty 服务启动成功");
    }
}
posted @   Kelvin's  阅读(4493)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示