【问题标题】:Spring Boot Microservices communication using Rest TemplateSpring Boot 微服务通信使用 Rest Template
【发布时间】:2021-03-18 15:42:40
【问题描述】:

我正在尝试实现 Rest Template 以与另一个微服务通信,但它无法正常工作,我是 Spring 新手,请帮助我完成此代码。

@GetMapping("/name")
    public Product name(){//@PathVariable String name){
        RestTemplate restTemplate = new RestTemplate();
       Product x = restTemplate.getForObject("http://localhost:8081/products", Product.class);
       return x;
    }

2021-03-18 10:31:34.072 错误 56434 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] :Servlet.service() for 带有路径 [] 的上下文中的 servlet [dispatcherServlet] 引发异常 [请求处理失败;嵌套异常是 org.springframework.web.client.RestClientException:出错时 提取类型 [class com.java.connect.entity.Product] 的响应 和内容类型 [application/json];嵌套异常是 org.springframework.http.converter.HttpMessageNotReadableException: JSON 解析错误:无法反序列化 com.java.connect.entity.Product 出 START_ARRAY 令牌;嵌套的 例外是 com.fasterxml.jackson.databind.exc.MismatchedInputException:不能 反序列化 com.java.connect.entity.Product 的实例 START_ARRAY 令牌 在 [来源:(PushbackInputStream);行:1,列:1]] 有根本原因

【问题讨论】:

    标签: spring microservices


    【解决方案1】:

    您得到的不是单一产品,而是一系列产品。

    所以你必须使用

    ResponsEntity<Product[]> response = restTemplate.getForObject("http://localhost:8081/products", Product[].class);
    Product[] products = response.getBody();
    

    但我认为这不是您想要的,我假设该名称将是其余端点的查询参数。所以你必须像这样传递名字:

    @GetMapping("/name")
    public Product name(){@PathVariable String name){
      RestTemplate restTemplate = new RestTemplate();
      Product x = restTemplate.getForObject("http://localhost:8081/products?name=" + name, Product.class);
      return x;
    }
    

    【讨论】:

      【解决方案2】:

      您需要进行以下更改才能使用 RestTemplate 获取产品列表。

      ResponseEntity<Product[]> response =
        restTemplate.getForEntity(
        "http://localhost:8080/products/",
        Product[].class);
      Product [] products = response.getBody();
      

      【讨论】:

        猜你喜欢
        • 2017-09-10
        • 2022-10-02
        • 2018-03-25
        • 2018-03-17
        • 2018-12-03
        • 1970-01-01
        • 2023-01-30
        • 1970-01-01
        • 2015-10-05
        相关资源
        最近更新 更多