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

相关推荐
学机械的鱼鱼1 小时前
一文读懂轮足翼复合机器人:结构特点与仿真学习路线规划
学习·机器人
知识分享小能手1 小时前
Hadoop学习教程,从入门到精通, 部署Hadoop 3.x — 知识点详解(2)
大数据·hadoop·学习
WIZnet1 小时前
W55RP20-EVB-MKR 模块 MicroPython 实战 (11):HTTP 协议与 OneNET 平台数据上云
网络·网络协议·http
许彰午1 小时前
微服务安全上下文的透明传递——ThreadLocal透传与HTTP头转发的完整链路
安全·http·微服务
星恒随风1 小时前
C++ 类和对象入门(三):拷贝构造、赋值运算符重载和深浅拷贝
开发语言·c++·笔记·学习
触底反弹2 小时前
从 Bun 到 DeepSeek:用 TypeScript 构建你的第一个 AI Agent
人工智能·http·typescript
tedcloud1232 小时前
Understand-Anything部署教程:打造AI代码理解平台
服务器·人工智能·学习·自动化·powerpoint
逆光的July2 小时前
Logback 学习笔记
笔记·学习·logback
SilentSamsara2 小时前
DuckDB + Python:嵌入式 OLAP 数据库的轻量分析实战
开发语言·数据库·python·微服务
数智工坊2 小时前
周志华《Machine Learning》学习笔记--第十三章--半监督学习
笔记·学习·机器学习