我有一個 Spring Boot 應用程式正在嘗試使用 Spring Cloud Gateway 訪問一些微服務。我正在使用的代碼基于在以下位置閱讀的說明:
https://betterjavacode.com/programming/how-to-use-api-gateway-with-spring-cloud
基本上,我的應用程式復制了該站點上提供的代碼,包括作者創建的兩個測驗微服務:
@RestController
@RequestMapping("/vendor")
public class VendorController
{
@GetMapping("/total")
public List vendors()
{
List list = new ArrayList<>();
list.add("CJI Consultants");
list.add("Signature Consultants");
list.add("Deloitte");
return list;
}
}
和
@RestController
@RequestMapping("/customer")
public class CustomerController
{
@GetMapping("/total")
public List customers()
{
List list = new ArrayList<>();
list.add("Microsoft");
list.add("Amazon");
list.add("Apple");
return list;
}
}
我的實際網關代碼與作者的類似:
包 com.betterjavacode.apigatewaydemo.config;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringCloudConfig
{
@Bean
public RouteLocator gatewayRoutes(RouteLocatorBuilder routeLocatorBuilder)
{
return routeLocatorBuilder.routes()
.route("customerModule", rt -> rt.path("/customer/**")
.uri("http://localhost:8081/"))
.route("vendorModule", rt -> rt.path("/vendor/**")
.uri("http://localhost:8082/"))
.build();
}
}
不幸的是,當我運行這個應用程式時,輸入正確的 URL:
http://localhost:8080/vendor/total
和
http://localhost:8080/customer/total
我收到 404 錯誤!
我似乎能夠通過網關訪問這兩個微服務的唯一方法是將路徑更改為“/**”。例如,為了訪問客戶微服務,我必須更改:
.route("customerModule", rt -> rt.path("/customer/**") .uri("http://localhost:8081/"))
到
v.route("customerModule", rt -> rt.path("/**") .uri("http://localhost:8081/"))
然后我可以毫無問題地看到客戶微服務輸出。當然,我不能對兩條路線使用相同的路徑。看起來這個網關只能處理一個使用“/**”路徑的路由。
我在這里錯過了什么嗎?有人可以說明為什么這不能正常作業嗎?我怎樣才能讓這個網關轉發到它應該去的路徑?
uj5u.com熱心網友回復:
您可以嘗試使用StripPrefix引數。
return routeLocatorBuilder.routes()
.route("customerModule", rt -> rt.path("/customer/**")
.filters(f -> f.stripPrefix(0))
.uri("http://localhost:8081/"))
.route("vendorModule", rt -> rt.path("/vendor/**")
.filters(f -> f.stripPrefix(0))
.uri("http://localhost:8082/"))
.build();
或者您可以洗掉 @RequestMapping("/customer") 和 @RequestMapping("/vendor") 因為它會在將前綴路徑發送到下游之前洗掉它。
uj5u.com熱心網友回復:
我相信我已經解決了這個問題。事實證明,由于未知原因,每當在網關中使用“/**”以外的路由時,URI 都不能包含 HTTP 前綴。
換句話說,而不是有一個路線:
route("customerModule", rt -> rt.path("/customer/**")
.uri("http://localhost:8081/"))
路由應該沒有 HTTP 前綴:
.route("customerModule", rt -> rt.path("/customer/**")
.uri("localhost:8081/"))
我不知道為什么會這樣,但確實如此。只要我格式化不帶前綴的 uri,我就可以訪問微服務。
我偶然發現了這一點。我很想知道為什么它會這樣作業,但至少應該記錄這個要求。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/409039.html
標籤:
上一篇:無法將路徑變數轉換為物件
