Gateway和spring-boot-starter-web的恩怨情仇

为什么取这个题目,其实与我踩到的坑有关,说起来这个坑非常神奇,这里面就涉及到Gateway和spring-boot-starter-web底层所依赖的技术不兼容的问题。

一、背景

SpringCloud 版本 ---- Finchley.SR2
SpringBoot 版本 ---- 2.0.6.RELEASE
如果同时在一个SpringBoot项目中引入了Gateway和spring-boot-starter-web,那么启动项目的时候会报错。

Error starting ApplicationContext. To display the conditions report re-run your application with ‘debug’ enabled.
2019-12-31 10:26:35.211 ERROR 13124 — [ main] o.s.b.d.LoggingFailureAnalysisReporter :


APPLICATION FAILED TO START


Description:
Parameter 0 of method modifyRequestBodyGatewayFilterFactory in org.springframework.cloud.gateway.config.GatewayAutoConfiguration required a bean of type ‘org.springframework.http.codec.ServerCodecConfigurer’ that could not be found.
Action:
Consider defining a bean of type ‘org.springframework.http.codec.ServerCodecConfigurer’ in your configuration.
Process finished with exit code 1

但是移除了spring-boot-starter-web 那么Gateway项目就可以启动了

二、问题分析

查看控制台打印日志:在这里插入图片描述
可以看到是 web 依赖下的 tomcat 容器启动失败,且打印出 nio 异常。

三、根源分析

3.1 原因分析

gateway应用的长链接,启动时基于netty-webflux ,gateway启动用的是webflux。然而Spring WebFlux 是 Spring Framework 5.0中引入的新的响应式web框架。与Spring MVC不同,它不需要Servlet API,是完全异步且非阻塞的,并且通过Reactor项目实现了Reactive Streams规范。

传统的spring-boot-starter-web,它的架构组合【spring-webmvc + Servlet + Tomcat】命令式的、同步阻塞的
响应式spring-webflux框架,它的架构组合【spring-webflux + Reactor + Netty】响应式的、异步非阻塞的

在一个web项目中存在基于两个不同的编程框架,互相冲突,从而导致项目启动报错。spring-boot-starter-web 和spring-boot-starter-webflux 相见分外眼红。不能配置在同一个pom.xml,或者不能同时用于同一个项目中。
如果一个项目中即引入Gateway又引入spring-boot-starter-web ,那么启动时默认使用了 spring-boot-starter-web 的内置容器,就会导致启动抛错,报错原因: spring-boot-starter-web 不支持gateway依赖非阻塞框架。

3.2 网关zuul和gateway区别

zuul基于同步webmvc(spring-boot-starter-web),而gateway是基于netty-webflux ,gateway启动用的是webflux,所以gateway和zuul不一样。

Zuul: 构建于 Servlet 2.5,兼容3.x,使用的是阻塞式的API,不支持长连接,比如 websockets。
Gateway构建于 Spring 5+,基于 Spring Boot 2.x 响应式的、非阻塞式的 API。同时,它支持 websockets,和 Spring 框架紧密集成

四、解决办法

4.1 排除web 内置容器

引入spring-boot-starter-web排除spring-boot-starter-tomcat

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <!-- Maven整个生命周期内排除内置容器,排除内置容器导出成war包可以让外部容器运行spring-boot项目-->
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

或者直接在gateway醒目中移除spring-boot-starter-web的全部引用

4.2 使用spring-webflux模块

webflux 有一个全新的非堵塞的函数式 Reactive Web 框架,可以用来构建异步的、非堵塞的、事件驱动的服务

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

五、总结

SpringCloud的生态非常的丰富,而且Spring的框架几经演变,出现了同步(springmvc)和异步(webflux),也出现了新技术webflux不兼容SpringMVC的情况,我们在从事java的spring开发应该要注意这些演变的区别,不断积累避免采坑。今天分享了gateway和spring-boot-starter-web的冲突,文章中有不对的地方,请多多指出,促使我们在学习中共同进步

猜你喜欢

转载自blog.csdn.net/Scalzdp/article/details/134876898