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

11 篇文章 0 订阅
2 篇文章 0 订阅

昨天在使用 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报错的问题。希望我的分享对你有所帮助。

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lishiyueup

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值