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

相关推荐
Linux-lucky1 小时前
21-Linux学习之旅之HTTPS和安全加固
linux·运维·学习·ubuntu·https
学运维的Kysan3 小时前
暑假运维学习打卡第二十六天8.17
学习
小小龙学IT4 小时前
Boost.Beast 深度实战:基于 Asio 的开源 C++ HTTP/WebSocket 协议库
c++·websocket·http
dear_bi_MyOnly4 小时前
AI人工智能分类识别——机器如何学习
人工智能·学习·分类
启雀AI6 小时前
培训平台移动端离线学习方案设计与实现:视频缓存、断点续传与进度同步的工程实践
android·学习·缓存·音视频·企业lms
ryan_9967 小时前
MCP Transport 完整指南:stdio 与 Streamable HTTP 到底怎样传消息
网络·网络协议·http
Bruce_Liuxiaowei8 小时前
从零到可运行:基于 Vue3 + FastAPI + DeepSeek-V3 的 AI 英语单词学习系统全栈实战
人工智能·python·学习·fastapi·全栈·智能体
zhangrelay9 小时前
ROS 2 Lyrical 第9章 计算机视觉与摄像头应用
linux·笔记·学习·ubuntu·机器人·ros2
雪的季节10 小时前
OPENCV学习(补充1)
人工智能·opencv·学习
zjnlswd11 小时前
C#学习笔记2 刘铁锰
笔记·学习