Spring WebFlux应用默认启动Tomcat而非Netty的问题咨询
问题分析与解决方案
你的问题核心原因是引入了spring-boot-starter-websocket依赖,这个依赖是为传统的Spring MVC(Servlet栈)设计的,它会自动传递引入spring-boot-starter-tomcat作为默认容器,直接覆盖了Spring WebFlux默认的Netty容器。
为什么会这样?
Spring Boot在判断使用哪种Web容器时,会根据classpath中的依赖自动检测:
- 当classpath中同时存在Servlet栈(比如
spring-boot-starter-websocket带来的Servlet相关依赖)和Reactive栈(spring-boot-starter-webflux)的依赖时,Spring Boot会优先选择Servlet栈的容器(Tomcat),而不是Netty。 - 即使你手动排除了
spring-boot-starter-webflux里的Tomcat依赖,spring-boot-starter-websocket依然会把Tomcat重新引入到项目中。
解决办法
移除
spring-boot-starter-websocket依赖
Spring WebFlux本身已经内置了对WebSocket的完整支持,不需要额外引入这个Servlet栈的starter。你可以直接使用WebFlux提供的WebSocket API,比如:- 用
@Controller配合@MessageMapping实现WebSocket消息处理 - 或者自定义
WebSocketHandler来处理WebSocket连接
- 用
(可选)明确指定Web应用类型
可以在application.properties或application.yml中添加配置,确保Spring Boot使用Reactive栈:spring.main.web-application-type: reactive不过只要移除了Servlet栈的冲突依赖,这个配置其实不是必须的,Spring Boot会自动识别并使用Netty。
验证效果
按照上述修改后,重新启动应用,你应该会在日志中看到Netty启动的信息,类似:
Netty started on port(s): 8080
内容的提问来源于stack exchange,提问作者The Coder
相关产品推荐
相关产品推荐

