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

相关推荐
南斯拉夫的铁托24 分钟前
YOLO学习笔记
笔记·学习·yolo
Bechamz25 分钟前
大数据开发学习Day27
java·大数据·学习
van久31 分钟前
Day21 第三周总结 + 用户模块收官复盘(可直接当学习笔记)
学习
Slow菜鸟37 分钟前
Docker 学习篇(五)| Docker 常用命令
学习·docker·容器
YJlio44 分钟前
8.2Windows 11 如何用 Xbox Game Bar 实时监测电脑性能?CPU、内存、GPU、显存与 FPS 瓶颈判断教程
windows·笔记·学习·chatgpt·架构·电脑·xbox
say_fall1 小时前
装软件慢到崩溃?用户创建总出错?Linux 工具避坑指南
linux·运维·服务器·c++·学习
Komorebi_99991 小时前
大模型学习day6
学习·大模型
-To be number.wan1 小时前
操作系统 | 进程调度机制全解析
学习·操作系统
talen_hx2962 小时前
OkHttpClient的最佳实践优化方案
java·笔记·学习
Byron__2 小时前
AI学习_05_LangChain使用
学习·langchain