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

相关推荐
东京老树根12 小时前
SAP学习笔记 - BTP SAP Build12 - SAP Build Content Package
笔记·学习
身如柳絮随风扬15 小时前
GET请求能带Body吗?GET与POST的核心区别全解析
http
雨辰AI15 小时前
SpringBoot3 + 人大金仓 V9 微服务监控实战|Prometheus+Grafana+SkyWalking 全链路监控
数据库·后端·微服务·grafana·prometheus·skywalking
幸福巡礼15 小时前
【LangChain 1.2 实战(一)】 概述
笔记·学习·langchain
知识分享小能手16 小时前
R语言入门学习教程,从入门到精通,R语言数据计算与分组统计(9)
开发语言·学习·r语言
lizhihai_9916 小时前
股市学习心得—半导体12种核心材料
大数据·人工智能·学习
sakiko_17 小时前
UIKit学习笔记3-布局、滚动视图、隐藏或显示视图
前端·笔记·学习·objective-c·swift·uikit
中冕—霍格沃兹软件开发测试17 小时前
区块链交易最终一致性测试的核心挑战与实践框架
微服务·架构·单元测试·区块链·集成测试·旅游
嵌入式-老费18 小时前
瑞芯微soc的学习和应用(题外话之esp32开发)
学习
辰同学ovo18 小时前
从全局登录状态管理学习 Redux
前端·javascript·学习·react.js