学而时习之,不亦说乎。|

微服务:如何在一个服务中调用另一个服务的接口(使用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 @   在博客做笔记的路人甲  阅读(596)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起