Spring Cloud gateway 运行报错:Please set spring.main.web-application-type=reactive or remove spring-boot

昨天在使用 Spring Cloud gateway 运行报错:“Please set spring.main.web-application-type=reactive or remove spring-boot-starter-web dependency”。经过一番分析与解决现在和大家分享一下解决办法。

首先,来了解一下这个报错的原因。该报错信息的意思是当前应用既引入了spring-cloud-starter-gateway包,又引入了spring-boot-starter-web包,这样会导致冲突。因为Spring Cloud Gateway本身是基于WebFlux构建的,而spring-boot-starter-web是基于Servlet容器的,两者不能同时存在。

那么,我们该如何解决这个问题呢?下面是解决方案的几个步骤:

步骤一:移除冲突的依赖

首先,我们需要在你的项目的pom.xml文件中找到spring-boot-starter-web依赖,并将其删除。这样就解决了冲突的问题。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

步骤二:设置web-application-type为reactive

接下来,我们需要在应用的配置文件application.yml或application.properties中添加以下配置:

spring:
  main:
    web-application-type: reactive

这样,我们告诉Spring Boot应用程序使用响应式的Web应用类型。

步骤三:使用GatewayFilter作为代替

如果你仍然希望使用Spring Boot的传统Servlet容器,而不是WebFlux,那么你可以考虑使用GatewayFilter来代替Spring Cloud Gateway。GatewayFilter是一种轻量级的网关解决方案,它可以与Spring Boot的Servlet容器一起使用,而无需引入WebFlux。

@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route(p -> p.path("/api")
            .filters(f -> f.filter(new MyFilter()))
            .uri("http://example.com"))
        .build();
}

上面的代码展示了使用GatewayFilter的示例,你可以根据自己的需求进行定制。

通过以上几个步骤,我们就成功解决了Spring Cloud Gateway报错的问题。希望我的分享对你有所帮助。

猜你喜欢

转载自blog.csdn.net/javamendou/article/details/131610726
今日推荐