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

相关推荐
天才奇男子8 小时前
HAProxy高级功能全解析
linux·运维·服务器·微服务·云原生
ASKED_20199 小时前
Langchain学习笔记一 -基础模块以及架构概览
笔记·学习·langchain
(❁´◡`❁)Jimmy(❁´◡`❁)9 小时前
Exgcd 学习笔记
笔记·学习·算法
云小逸11 小时前
【nmap源码学习】 Nmap网络扫描工具深度解析:从基础参数到核心扫描逻辑
网络·数据库·学习
盐焗西兰花13 小时前
鸿蒙学习实战之路-Reader Kit构建阅读器最佳实践
学习·华为·harmonyos
深蓝海拓13 小时前
PySide6从0开始学习的笔记(二十七) 日志管理
笔记·python·学习·pyqt
慎独41314 小时前
科学赋能,让孩子专注高效爱上学习
学习
凯子坚持 c14 小时前
C++基于微服务脚手架的视频点播系统---客户端(4)
数据库·c++·微服务
LGL6030A14 小时前
Java学习历程26——线程安全
java·开发语言·学习
老百姓懂点AI14 小时前
[微服务] Istio流量治理:智能体来了(西南总部)AI调度官的熔断策略与AI agent指挥官的混沌工程
人工智能·微服务·istio