【SpringCloud】01-远程调用

1. RestTemplate

    1. 注册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();
    }

}
    1. 在代码中引入Bean
java 复制代码
// 推荐使用构造函数注入, 使用lombook的@RequiredArgsConstructor进行注入
    private final RestTemplate restTemplate;
    1. 远程调用
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();
相关推荐
玹外之音1 小时前
Spring AI 实战:手把手教你构建支持多会话管理的智能聊天服务
java·spring
callJJ2 小时前
Spring Bean 生命周期详解——从出生到销毁,结合源码全程追踪
java·后端·spring·bean·八股文
怒放吧德德2 小时前
AsyncTool + SpringBoot:轻量级异步编排最佳实践
java·后端
毅炼2 小时前
Java 集合常见问题总结(1)
java·后端
知识即是力量ol2 小时前
口语八股——Spring 面试实战指南(一):核心概念篇、AOP 篇
java·spring·面试·aop·八股·核心概念篇
utmhikari3 小时前
【架构艺术】治理后端稳定性的一些实战经验
java·开发语言·后端·架构·系统架构·稳定性·后端开发
dfyx9993 小时前
Maven Spring框架依赖包
java·spring·maven
undefinedType3 小时前
Rails ActiveSupport::Cache 缓存存储详解
后端
茶杯梦轩3 小时前
从零起步学习并发编程 || 第二章:多线程与死锁在项目中的应用示例
java·服务器·后端
大尚来也3 小时前
深入理解 Android 消息机制:Handler、Looper 与 MessageQueue 的协同工作原理
后端