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

Yesterday I was using Spring Cloud gateway and got an error: "Please set spring.main.web-application-type=reactive or remove spring-boot-starter-web dependency". After some analysis and solution, I would like to share the solution with you.

First, let’s understand the reason for this error. The error message means that the current application has introduced both the spring-cloud-starter-gateway package and the spring-boot-starter-web package, which will cause a conflict. Because Spring Cloud Gateway itself is built based on WebFlux, and spring-boot-starter-web is based on the Servlet container, the two cannot exist at the same time.

So, how do we solve this problem? Here are a few steps to the solution:

Step 1: Remove conflicting dependencies

First, we need to find the spring-boot-starter-web dependency in your project's pom.xml file and delete it. This solves the conflict problem.

<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>

Step 2: Set web-application-type to reactive

Next, we need to add the following configuration to the application’s configuration file application.yml or application.properties:

spring:
  main:
    web-application-type: reactive

In this way, we tell the Spring Boot application to use the responsive web application type.

Step 3: Use GatewayFilter instead

If you still want to use Spring Boot's traditional Servlet container instead of WebFlux, then you can consider using GatewayFilter instead of Spring Cloud Gateway. GatewayFilter is a lightweight gateway solution that can be used with Spring Boot's Servlet container without introducing 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();
}

The above code shows an example of using GatewayFilter, which you can customize according to your needs.

Through the above steps, we successfully solved the problem of Spring Cloud Gateway error. I hope my sharing will be helpful to you.

Guess you like

Origin blog.csdn.net/javamendou/article/details/131610726