boot微服务通信

ep6jt1vc  于 2021-07-16  发布在  Java
关注(0)|答案(2)|浏览(215)

我正在尝试实现rest模板以与另一个微服务对话,但它不能正常工作,我是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[dispatcherservlet]的servlet.service()引发异常[请求处理失败;嵌套的异常是org.springframework.web.client.restclientexception:提取类型[class com.java.connect.entity.product]和内容类型[application/json]的响应时出错;嵌套异常为org.springframework.http.converter.httpMessageNotradableException:json分析错误:无法反序列化的示例 com.java.connect.entity.Product 启动外\u数组令牌;嵌套异常为com.fasterxml.jackson.databind.exc.missmatchdinputException:无法反序列化的示例 com.java.connect.entity.Product [source:(pushbackinputstream)处的启动\u数组令牌不足;行:1,列:1]]带根本原因

sbtkgmzw

sbtkgmzw1#

你不会得到一个单一的产品,而是一系列的产品。
所以你必须使用

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

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

@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;
}
wz1wpwve

wz1wpwve2#

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

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

相关问题