微服务学习: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方法阻塞获取响应体的内容。

相关推荐
峥嵘life37 分钟前
Android GMS 开机向导横竖屏切换配置总结
android·学习
六bring个六1 小时前
链表学习(常规链表)
数据结构·学习·链表
say_fall1 小时前
【Git 精品详解】企业规范:企业级开发模型、Git Flow、发版流程规范、Code Owner 制度、事故应急回滚
大数据·linux·服务器·git·学习·elasticsearch
kgduu1 小时前
react-redux学习笔记
笔记·学习·react.js
诗句藏于尽头1 小时前
Ai-3D音乐播放器-Mineradio -VibeCoding大赏-新增歌词字体自定义上传功能(个人学习)
学习
TE-茶叶蛋2 小时前
Node.js-Phase 1 学习总结:CLI 文件管理系统
学习·node.js
Waay11 小时前
面试口述版:个人对 Prometheus 完整理解
运维·学习·云原生·面试·职场和发展·kubernetes·prometheus
一楼的猫13 小时前
AI写作合规技术方案:平台检测机制分析与规避策略
人工智能·学习·机器学习·ai写作
四月天4315 小时前
web安全-SSTI(服务器模板注入)
笔记·学习·web安全·网络安全
网络与设备以及操作系统学习使用者15 小时前
相对论核心原理详解
学习·深度优先