可以在启动类或者配置类中开始写
在启动类中写:
- 创建 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();
}