我有一個名為 carrental-crud 的 spring-boot 專案,帶有一個 h2 記憶體資料庫,我想從另一個名為 carrental-api 的專案訪問其中一個端點。
我在其他端點上為此使用了 webClientBuilder,但是當我嘗試在郵遞員中使用它時,它會以錯誤的請求拋出狀態 500。
我使用 JPRepository 通過查詢訪問 h2 db,這就是我的 orderRepository 的樣子:
@Transactional
@Query(nativeQuery = true,value = "select count(*) from TBL_ORDER WHERE CUSTOMER_ID=?1")
public int getTotalOrders(long customerId);
然后在我的 adminCustomerService 類中,我像這樣使用它:
public int getTotalOrders(long customerId) {
loggerService.writeLoggerMsg("LISTED TOTAL ORDERS FOR A CUSTOMER");
return orderRepository.getTotalOrders(customerId);
}
然后在我的 adminCustomerController 中:
@GetMapping(path = "/totalorders")
public int getTotalOrders(@RequestBody Customer customer) {
return adminCustomerService.getTotalOrders(customer.getCustomerId());
}
在我的郵遞員請求正文中,我寫道:
{
"customerId": 2
}
這在我的 carrental-crud 中有效,但是如何在我的 carrental-api 中重新創建它?
并在郵遞員中使用相同的請求正文,但我不斷收到錯誤狀態 500 的錯誤請求
編輯:我設法通過使用引數而不是請求正文來使其作業。
這是我的 adminCustomerService 的樣子:
public int getTotalOrders(long customerId) {
int orders = webClientBuilder.build()
.get()
.uri("http://localhost:8081/crud/v1/totalorders/" customerId)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<Integer>() {})
.log()
.block();
return orders;
}
還有我的 adminCustomerController :
@GetMapping(path = "/totalorders/{customerId}")
public int getTotalOrders(@PathVariable long customerId) {
return adminCustomerService.getTotalOrders(customerId);
}
uj5u.com熱心網友回復:
問題在于,當您應該發送類似于您顯示的 JSON 的內容時,您只是在程式化呼叫customerId中將其作為 aLong發送。解決這個問題的最簡單方法是創建一個與此類 JSON 結構匹配的類:
public class CustomerRequest {
private long customerId;
public CustomerRequest(long customerId) {
this.customerId = customerId;
}
public long getCustomerId() {
return customerId;
}
}
然后你需要在呼叫API時創建一個這樣的類的實體,如下所示:
public Flux<Integer> getTotalOrders(long customerId) {
loggerService.writeLoggerMsg("LISTED TOTAL ORDERS FOR A CUSTOMER");
return ((RequestBodySpec) webClientBuilder
.build()
.get()
.uri("localhost:8081/crud/v1/totalorders"))
.body(Flux.just(new CustomerRequest(customerId)), CustomerRequest.class)
.retrieve()
.bodyToFlux(Integer.class);
}
盡管如此,我還是建議您在端點中采用更 RESTful 的方法,并在 GET 請求中使用路徑引數而不是請求正文。大致如下:
@GetMapping(path = "/customers/{customerId}/total-orders")
public int getTotalOrders(@PathVariable long customerId) {
return adminCustomerService.getTotalOrders(customerId);
}
然后您將向此端點發出請求,如下所示:
public Flux<Integer> getTotalOrders(long customerId) {
loggerService.writeLoggerMsg("LISTED TOTAL ORDERS FOR A CUSTOMER");
return webClientBuilder
.build()
.get()
.uri("localhost:8081/crud/v1/customers/{customerId}/total-orders", customerId))
.retrieve()
.bodyToFlux(Integer.class);
}
我建議您閱讀以下在線資源:
- https://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/
- https://www.baeldung.com/spring-pathvariable
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/394224.html
