微服务学习:RestTemplate&WebClient发起的http请求实现远程调用

http请求做远程调用是与语言无关的调用,只要知道对方的ip,端口,接口路径,请求参数即可

启动类中配置:

java 复制代码
@Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

Sevice中书写方法

get

java 复制代码
 @Autowired
    private RestTemplate restTemplate;

    public Order queryOrderById(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);
        //2.查询到了用户id
        Long userId = order.getUserId();
        //发起一个请求访问http://localhost:8081/user/5
        String url ="http://localhost:8081/user/"+userId;
        User user = restTemplate.getForObject(url, User.class);
        //封装
        order.setUser(user);
        // 4.返回
        return order;
    }

建议

从Spring 5开始,官方推荐使用WebClient代替RestTemplate作为进行HTTP请求的工具。WebClient是一个非阻塞、响应式的HTTP客户端,更适合于构建高性能、异步的应用程序。因此,在新的Spring项目中,建议使用WebClient替代RestTemplate

使用WebClient发送GET请求的示例:

java 复制代码
WebClient webClient = WebClient.create();
String url = "https://api.example.com/users";
String responseBody = webClient.get()
        .uri(url)
        .retrieve()
        .bodyToMono(String.class)
        .block();

使用WebClient发送GET请求到指定的URL,并通过bodyToMono方法将响应体转换为字符串类型。最后,通过调用block方法阻塞获取响应体的内容。

相关推荐
~kiss~1 小时前
LLM 的 层归一化(稳定训练) - Layer Normalization & RMSNorm
学习
MartinYeung52 小时前
[论文学习]LLM-based AI Agent 安全威胁与防御系统性综述
人工智能·学习·安全
巴巴媛6662 小时前
STM32学习笔记【36.CAN收发实验】
笔记·stm32·学习
光学补偿3 小时前
文件IO的前世今生
开发语言·学习·面试·java-ee
xian_wwq3 小时前
【学习笔记】分布式推理:TP / PP / EP / CP 并行策略详解(20/35)
笔记·分布式·学习·ai
凉、介3 小时前
Linux 设备驱动匹配机制
linux·笔记·单片机·学习·操作系统·嵌入式
大师兄66683 小时前
HarmonyOS7 HTTP 网络请求封装:统一拦截器实战
网络·网络协议·http·arkui·harmonyos7·实战讲解
bu_shuo4 小时前
计算机二级学习-软件工程基础
学习·软件工程
worilb4 小时前
Spring Cloud 学习与实践(15):使用 TraceId 与 MDC 串联微服务日志
学习·spring cloud·微服务
韩曙亮4 小时前
【Flutter】iOS 网络权限设置 ② ( 配置 iOS 平台可使用 HTTP 访问 | ATS 网络安全强制规范 )
网络·flutter·http·ios·https·网络权限·ats