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

微服务调用500错误及Jackson序列化异常排查求助

问题修复方案:订单微服务调用库存微服务500错误及序列化异常处理

问题根源

库存微服务的isInStock方法错误返回List<InventoryRepository>类型,checkstock方法直接返回inventoryRepository实例,而非业务所需的InventoryResponse DTO对象。Spring Data Repository是动态代理类,包含无法被Jackson序列化的内部类(如TransactionalRepositoryProxyPostProcessor$RepositoryAnnotationTransactionAttributeSource),导致接口返回时抛出序列化异常,触发订单微服务调用的500错误。

修复步骤

  • 修正Service层返回值

    1. 调整checkstock方法,替换返回值为InventoryResponse对象:
      // 错误写法
      public InventoryRepository checkstock(String skuCode) {
          return inventoryRepository;
      }
      
      // 正确写法
      public InventoryResponse checkstock(String skuCode) {
          Inventory inventory = inventoryRepository.findBySkuCode(skuCode);
          return new InventoryResponse(inventory.getSkuCode(), inventory.getQuantity() > 0);
      }
      
    2. 修改isInStock方法的返回类型为List<InventoryResponse>,并返回DTO列表:
      // 错误写法
      public List<InventoryRepository> isInStock(List<String> skuCodes) {
          // 返回Repository实例列表的错误逻辑
      }
      
      // 正确写法
      public List<InventoryResponse> isInStock(List<String> skuCodes) {
          return inventoryRepository.findBySkuCodeIn(skuCodes).stream()
              .map(inventory -> new InventoryResponse(inventory.getSkuCode(), inventory.getQuantity() > 0))
              .collect(Collectors.toList());
      }
      
  • 修正Controller层返回值
    调整Controller中isInStock方法的返回类型,与Service层保持一致,确保接口输出InventoryResponse数组:

    // Spring WebMVC场景
    @GetMapping("/api/inventory")
    public List<InventoryResponse> isInStock(@RequestParam List<String> skuCodes) {
        return inventoryService.isInStock(skuCodes);
    }
    
    // Spring WebFlux场景
    @GetMapping("/api/inventory")
    public Flux<InventoryResponse> isInStock(@RequestParam List<String> skuCodes) {
        return inventoryService.isInStock(skuCodes);
    }
    
  • 确保DTO可序列化
    保证InventoryResponse是标准POJO,具备无参构造、getter/setter方法(可通过Lombok简化):

    @Data
    public class InventoryResponse {
        private String skuCode;
        private boolean isInStock;
    
        public InventoryResponse() {}
    
        public InventoryResponse(String skuCode, boolean isInStock) {
            this.skuCode = skuCode;
            this.isInStock = isInStock;
        }
    }
    
  • 验证修复效果

    1. 直接调用库存微服务的http://localhost:9091/api/inventory/接口,确认返回格式正确的JSON数组,无序列化异常。
    2. 重启订单微服务,通过WebClient调用该接口,验证不再出现WebClientResponseException$InternalServerError错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:30:13