微服务:如何在一个服务中调用另一个服务的接口(使用http请求)?

也就是在Java代码中发起http请求,并获取响应信息。

 


 基础方式,存在硬编码问题

一、注册RestTemplate对象

@Bean
public RestTemplate restTemplate(){
    return new RestTemplate();
}

二、使用RestTemplate发起请求

//注入restTemplate对象
@Autowired
private RestTempate restTemplate;

public void test(){
    //请求地址
    String url = "http://localhost:8080/user/1";
    //发起请求,获取响应
    //get请求,获取用户信息
    User user = restTemplate.getForObject(url,User.class);
}

 

posted @ 2023-04-14 11:47  在博客做笔记的路人甲  阅读(483)  评论(0编辑  收藏  举报