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

相关推荐
马***4118 小时前
适配成人英语学习痛点,打造落地性强的学习辅助方式
人工智能·学习
小拉达不是臭老鼠10 小时前
Unity学习_ScriptableObject
学习·unity
MartinYeung511 小时前
[论文学习]LLM 与其他 AI 模型的隐私考量:输入与输出隐私框架方法
人工智能·学习
(●—●)橘子……12 小时前
力扣第503场周赛练习理解
python·学习·算法·leetcode·职场和发展·周赛
AOwhisky13 小时前
MySQL 学习笔记(第一期):数据库基础与 MySQL 初探
运维·数据库·笔记·学习·mysql·云计算
try2find14 小时前
Agent学习之补充my_plan_solve_agent
学习
想你依然心痛15 小时前
HarmonyOS 6(API 23)实战:打造“光码智学舱“——AI编程学习新范式
学习·ar·ai编程·harmonyos·智能体
@PHARAOH15 小时前
WHAT - NextAuth 权限认证机制
前端·微服务·服务端
二营长116 小时前
后端请求https协议接口地址报错
网络协议·http·https
一口吃俩胖子16 小时前
【脉宽调制DCDC功率变换学习笔记023】渐进分析法
笔记·学习