如何在两个服务当中发起http请求 ~ langhai

林书豪
2023-04-10 07:10:36
如何在两个服务当中发起http请求 浪海值:1045度
文章标签:微服务相关
文章摘要:http请求小工具 RestTemplate
使用新的显示器:新的显示器 如果遇到图片单击即可放大/缩小。

http请求小工具 RestTemplate

// 在任意配置类或者启动类中,创建出RestTemplate类,把这个对象交由spring进行管理。

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

// 在需要用到的地方,直接注入即可。

    @Autowired
    private RestTemplate restTemplate;

// 接下来就可以直接在方法中使用他的API,以下的例子是启动了两个java服务,order订单服务中需要访问user用户服务。

    String url = "http://localhost:8081/langhaiBlogs/user/" + userId;
    User user = restTemplate.getForObject(url, User.class);

// 这里对上述代码简单阐述一下,首先user用户服务提供的是一个get请求方式的接口,直接通过用户的id就能获取到用户的详情信息。发起http请求对两个服务由什么语言编写并没有关系,只要知道调用服务接口的信息即可。

// 文章原创 QQ676558206

提交评论