1. RestTemplate
-
- 注册Bean
java
@SpringBootApplication
public class CartServiceApplication {
public static void main(String[] args) {
SpringApplication.run(CartServiceApplication.class, args);
System.out.println("cart启动成功");
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
-
- 在代码中引入Bean
java
// 推荐使用构造函数注入, 使用lombook的@RequiredArgsConstructor进行注入
private final RestTemplate restTemplate;
-
- 远程调用
java
// 1.获取商品id
Set<Long> itemIds = vos.stream().map(CartVO::getItemId).collect(Collectors.toSet());
// 2.查询商品
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, ","))
);
if (!response.getStatusCode().is2xxSuccessful()) {
return;
}
List<ItemDTO> items = response.getBody();