You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot WebClient调用Price微服务出现block终止错误求助

问题排查与解决方案

1. 核对Price微服务自定义方法的路径规则

Spring Data Rest对自定义Repository方法的暴露路径有严格要求:

  • 必须在Repository方法上标注@RestResource指定path和rel,示例:
    @RepositoryRestResource
    public interface PriceRepository extends JpaRepository<Price, Long> {
        @RestResource(path = "recalculate-by-vehicle-id", rel = "recalculateByVehicleId")
        void recalculatePriceByVehicleId(@Param("vehicleId") Long vehicleId);
    }
    
  • 调用路径必须是[基础URL]/prices/search/[path]?vehicleId=XXX,WebClient的URI要完全匹配,不能写错路径或参数名。

2. 验证WebClient的基础URL配置

确认Vehicle服务中WebClient配置的Price微服务地址完全正确:

@Bean
public WebClient priceWebClient(WebClient.Builder builder) {
    // 需和Price微服务的端口、上下文路径一致,默认Spring Data Rest根路径为/
    return builder.baseUrl("http://price-service:8080") 
                  .build();
}

如果Price微服务配置了server.servlet.context-path=/api,则基础URL要改成http://price-service:8080/api。

3. 检查请求方式与方法注解匹配

  • 如果自定义方法是修改操作(比如更新价格),必须在Repository方法上添加@Modifying、@Transactional,并通过@RestResource指定请求方法为POST:
    @Modifying
    @Transactional
    @RestResource(path = "recalculate-by-vehicle-id", rel = "recalculateByVehicleId", method = RequestMethod.POST)
    void recalculatePriceByVehicleId(@Param("vehicleId") Long vehicleId);
    
  • WebClient调用时要对应使用POST方法,参数通过queryParam传递:
    webClient.post()
             .uri(uriBuilder -> uriBuilder.path("/prices/search/recalculate-by-vehicle-id")
                                         .queryParam("vehicleId", deletedVehicleId)
                                         .build())
             .retrieve()
             .bodyToMono(Void.class)
             .block();
    
    若为查询类操作,使用GET请求即可。

4. 直接验证Price微服务接口可用性

绕过WebClient,用curl或Postman直接调用Price微服务的接口:

curl http://localhost:8080/prices/search/recalculate-by-vehicle-id?vehicleId=123

如果直接调用也返回404,说明问题出在Price微服务的方法定义或配置上,与Vehicle服务的WebClient无关。

5. 补充WebClient错误处理以定位细节

当前代码未处理404错误,block()会直接抛出模糊异常,建议添加错误处理获取详细信息:

webClient.get()
         .uri(...)
         .retrieve()
         .onStatus(HttpStatus::is4xxClientError, response -> {
             return response.bodyToMono(String.class)
                            .flatMap(errorBody -> Mono.error(new RuntimeException("Price服务返回404: " + errorBody)));
         })
         .bodyToMono(Void.class)
         .block();

6. 确认传递的车辆ID有效性

检查删除车辆时获取的deletedVehicleId是否为有效非null值,可在代码中打印日志确认参数正确性。

内容的提问来源于stack exchange,提问作者Othello

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 17:08:08