使用RestTemplate完成远程调用

可以在启动类或者配置类中开始写

在启动类中写:

  1. 创建 RestTemplate 实例:
  • 创建一个新的 RestTemplate 实例,并将其返回。        
  •  RestTemplate 是 Spring 提供的一个简单的 HTTP 客户端,用于发起 HTTP 请求。

    2.将 RestTemplate 注入 Spring 容器:

  • 使用 @Bean 注解将 RestTemplate 实例注册到 Spring 容器中。
  • 这意味着你可以在其他组件中通过依赖注入的方式获取这个 RestTemplate 实例。

   3.方便依赖注入:

  •  其他组件可以通过 @Autowired 注解自动注入这个 RestTemplate 实例,从而方便地发起 HTTP 请求。       
@SpringBootApplication
@MapperScan("cn.jj..mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(CartApplication.class, args);
    }

    //创建 RestTemplate 实例
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

在需要调用的地方写:

 ResponseEntity<List<ItemDTO>> response = restTemplate.exchange(
                "http://localhost:8081/items?ids={ids}",
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<ItemDTO>>() {
                },
                Map.of("ids", CollUtil.join(itemIds, ","))
        );


@Service
@RequiredArgsConstructor    //必备构造函数

public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {

  

    private final  RestTemplate restTemplate;


    private void handleCartItems(List<CartVO> vos) {
        // TODO 1.获取商品id
        Set<Long> itemIds = vos.stream().map(CartVO::getItemId).collect(Collectors.toSet());
        // 2.查询商品
        //2.1 利用restTemplate发起http请求,得到http的响应
        //List<ItemDTO> items = itemService.queryItemByIds(itemIds);
        ResponseEntity<List<ItemDTO>> response = restTemplate.exchange(
                "http://localhost:8081/items?ids={ids}",
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<ItemDTO>>() {
                },
                Map.of("ids", CollUtil.join(itemIds, ","))
        );
        //2.2 解析响应
        if (! response.getStatusCode().is2xxSuccessful()){
            //查询失败
            return;

        }
        List<ItemDTO> items = response.getBody();


   
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值