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

相关推荐
努力努力再努力wz10 分钟前
【Linux网络系列】:打破 HTTP 明文诅咒,在Linux 下用 C++ 手搓 HTTPS 服务器全过程!(附实现源码)
linux·服务器·网络·数据结构·c++·http·https
charlie11451419111 分钟前
现代嵌入式 C++——自定义删除器(Custom Deleter)
开发语言·c++·笔记·学习·嵌入式
QiZhang | UESTC15 分钟前
学习日记day70
学习
没有bug.的程序员29 分钟前
Spring Cloud Stream:消息驱动微服务的实战与 Kafka 集成终极指南
java·微服务·架构·kafka·stream·springcloud·消息驱动
星期五不见面33 分钟前
嵌入式学习!(一)C++学习-STL(21)-26/1/27
开发语言·c++·学习
知识分享小能手34 分钟前
Oracle 19c入门学习教程,从入门到精通,Oracle系统调优 —— 内存结构与参数优化详解(15)
数据库·学习·oracle
??(lxy)36 分钟前
GIT使用学习
git·学习
im_AMBER37 分钟前
Leetcode 108 交换链表中的节点
数据结构·笔记·学习·算法·leetcode·链表
再卷还是菜42 分钟前
网安渗透学习小结--sql注入
数据库·sql·学习
LaoZhangGong1231 小时前
学习TCP/IP的第8步:紧急数据
网络·stm32·单片机·学习·tcp/ip·以太网