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

发布时间 2023-04-14 11:51:51作者: 在博客做笔记的路人甲

也就是在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);
}