昨天在使用 Spring Cloud gateway 運行報錯:“Please set spring.main.web-application-type=reactive or remove spring-boot-starter-web dependency”。經(jīng)過一番分析與解決現(xiàn)在和大家分享一下解決辦法。
首先,來了解一下這個報錯的原因。該報錯信息的意思是當(dāng)前應(yīng)用既引入了spring-cloud-starter-gateway包,又引入了spring-boot-starter-web包,這樣會導(dǎo)致沖突。因為Spring Cloud Gateway本身是基于WebFlux構(gòu)建的,而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>
步驟二:設(shè)置web-application-type為reactive
接下來,我們需要在應(yīng)用的配置文件application.yml或application.properties中添加以下配置:
spring:
main:
web-application-type: reactive
這樣,我們告訴Spring Boot應(yīng)用程序使用響應(yīng)式的Web應(yīng)用類型。
步驟三:使用GatewayFilter作為代替
如果你仍然希望使用Spring Boot的傳統(tǒng)Servlet容器,而不是WebFlux,那么你可以考慮使用GatewayFilter來代替Spring Cloud Gateway。GatewayFilter是一種輕量級的網(wǎng)關(guān)解決方案,它可以與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的示例,你可以根據(jù)自己的需求進行定制。文章來源:http://www.zghlxwxcb.cn/news/detail-821802.html
通過以上幾個步驟,我們就成功解決了Spring Cloud Gateway報錯的問題。希望我的分享對你有所幫助。文章來源地址http://www.zghlxwxcb.cn/news/detail-821802.html
到了這里,關(guān)于Spring Cloud gateway 運行報錯:Please set spring.main.web-application-type=reactive or remove spring-boot的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!