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

相关推荐
南浦别a11 小时前
第三十一天--继续学习--TreeSet排序方式和HashSet
学习
承渊政道11 小时前
C++学习之旅【⽤哈希表封装myunordered_map和myunordered_set以及位图和布隆过滤器介绍】
数据结构·c++·学习·哈希算法·散列表·hash-index·图搜索算法
金山几座11 小时前
C#学习记录-变量与类型
学习·c#
飞Link12 小时前
深度解析 InfoNCE:对比学习背后的“核心功臣”
python·学习·数据挖掘·回归
yangyanping2010812 小时前
Linux学习四之 rm 命令详解
linux·运维·学习
怪侠_岭南一只猿12 小时前
爬虫工程师学习路径 · 阶段四:反爬虫对抗(完整学习文档)
css·爬虫·python·学习·html
CappuccinoRose12 小时前
MATLAB学习文档 - 汇总篇
学习·算法·matlab
不灭锦鲤12 小时前
网络安全学习第47天
学习·web安全
zhouping@13 小时前
BUUCTFweb
学习·web安全·php
观书喜夜长13 小时前
SQLMap 入门实战指南:原理、命令详解与防御(攻防世界-inget)
学习·web安全·网络安全