netty如何“嵌入”到springboot中

       为什么说是netty如何“嵌入”到springboot中,因为netty本身需要绑定一个端口,需要新线程去跑,如果你直接把netty的类作为组件加入springboot的话,那么当加载netty时,netty启动后就把springboot给阻塞掉了,http请求都无法处理,特别是使用netty实现websocket的时候,还不支持springMVC,所以netty更应该作为一个独立的maven项目去构建部署。
       但是有时候懒省事就让netty随着springboot一起启动,也是有方法的:

@SpringBootApplication
public class GroupChatStart implements CommandLineRunner {

    @Autowired
    WebSocketServer webSocketServer;

    public static void main(String[] args){
        SpringApplication.run(GroupChatStart.class,args);
    }

    @Override
    public void run(String... args) throws Exception {
        webSocketServer.run();
    }
}

       让启动类去实现CommandLineRunner接口,重写run方法,这个run方法应该就是新开了一个线程去跑别的代码去了,不影响springboot的运行,这里是将netty服务器的启动类作为组件添加到了容器中,以注入的方式启动,因为在netty的启动类里要使用@Value导入配置信息,但要注意netty启动的代码不要放到构造里,否则就又会把springboot阻塞掉。

猜你喜欢

转载自blog.csdn.net/weixin_42822484/article/details/106537950