RestTemplate 远程调用
🌉

RestTemplate 远程调用

Created
May 3, 2024 09:32 AM
Tags

RestTemplate

Spring 提供了 RestTemplate API,实现同步阻塞的发送 Http 请求,进行远程调用。
支持常见的 GetPostPutDelete 请求,如果请求参数比较复杂,还可以使用 exchange 方法来构造请求。
在配置类中将 RestTemplate 注册为一个 Bean:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class RemoteCallConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
利用 RestTemplate 发送 http 请求与前端 ajax 发送请求非常相似,包含四部分信息:
  • 请求方式
  • 请求路径
  • 请求参数
  • 返回值类型
在下面的示例中,itemService 被拆分为一个单独的微服务,所以无法在本地调用,用RestTemplate 进行远程调用请求:
private void handleCartItems(List<CartVO> vos) { // TODO 1.获取商品id Set<Long> itemIds = vos.stream().map(CartVO::getItemId).collect(Collectors.toSet()); // 2.查询商品 // List<ItemDTO> items = itemService.queryItemByIds(itemIds); // 2.1.利用RestTemplate发起http请求,得到http的响应 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(); if (CollUtils.isEmpty(items)) { return; } // 3.转为 id 到 item的map Map<Long, ItemDTO> itemMap = items.stream().collect(Collectors.toMap(ItemDTO::getId, Function.identity())); // 4.写入vo for (CartVO v : vos) { ItemDTO item = itemMap.get(v.getItemId()); if (item == null) { continue; } v.setNewPrice(item.getPrice()); v.setStatus(item.getStatus()); v.setStock(item.getStock()); } }
核心:
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, ",")) );
其中 new ParameterizedTypeReference<List<ItemDTO>>() {} 解决 List<ItemDTO> 无法得到带范型的 class 的问题
Spring 对其的介绍包含如下一句:
请考虑使用 org.springframework.web.react .client. webclient,它有更现代的API,支持同步、异步和流场景。

WebClient