【Spring Boot】如何通过RestTemplate获取另一个服务的接口返回信息

  1. 背景
    1. 在查询订单信息的时候,需要获取用户的信息,同时订单和用户分属于不同的服务中,并且服务的数据库的数据分开的,其直接连接数据库并操作数据库是不可以的。那我们可以通过RestTemplate对象请求另一个服务的API接口获取相关的响应数据,然后再封装返回
  2. 在Spring Boot中我们可以先注册RestTemplate的Bean
    1. package com.app.order.config;
      
      import lombok.extern.slf4j.Slf4j;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.web.client.RestTemplate;
      
      /**
       * webmvc的相关配置
       *
       * @author Administrator
       */
      @Configuration
      @Slf4j
      public class WebMvcConfig {
      
          /**
           * 注入RestTemplate的Bean
           *
           * @return 返回RestTemplate
           */
          @Bean
          public RestTemplate restTemplate() {
              return new RestTemplate();
          }
      
      }
      
  3. 在使用的地方注入RestTemplate对象
    1.     /**
           * 结合@RequiredArgsConstructor进行构造器注入
           */
          private final RestTemplate restTemplate;
  4. 在查询的方法处使用远程调用
    1. 
          /**
           * 根据id查询订单信息
           *
           * @param id 订单id
           * @return 订单信息
           */
          @GetMapping("/{id}")
          public ResultBean<OrderVo> getById(@PathVariable Long id) {
              log.info("根据id查询订单信息...");
              Order order = orderService.getById(id);
              if (order != null) {
                  OrderVo orderVo = new OrderVo();
                  BeanUtil.copyProperties(order, orderVo);
                  // 远程查找用户服务获取用户名信息
                  // url地址
                  String url = "http://127.0.0.1:8080/users/" + order.getUserId();
                  // 发起远程调用
                  ResultBean resultBean = restTemplate.getForObject(url, ResultBean.class);
                  if (resultBean != null) {
                      UserVo userVo = new UserVo();
                      BeanUtil.copyProperties(resultBean.getData(), userVo);
                      orderVo.setUsername(userVo.getUsername());
                  }
                  return ResultBean.success(orderVo);
              }
              return ResultBean.error("没有查询到对应订单信息");
          }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值