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

相关推荐
哲Zheᗜe༘14 分钟前
学习Ansible Playbook 核心语法
网络·学习·ansible
('-')18 分钟前
《从根上理解MySQL是怎样运行的》第三章学习笔记
笔记·学习·mysql
后端小张1 小时前
【JAVA 进阶】Spring Cloud 微服务全栈实践:从认知到落地
java·开发语言·spring boot·spring·spring cloud·微服务·原理
Nan_Shu_6144 小时前
学习:ES6(2)
前端·学习·es6
河铃旅鹿5 小时前
Android开发-java版:Framgent
android·java·笔记·学习
自动化代码美学8 小时前
【Python3.13】官网学习之控制流
开发语言·windows·python·学习
AA陈超8 小时前
ASC学习笔记0020:用于定义角色或Actor的默认属性值
c++·笔记·学习·ue5·虚幻引擎
2501_9411495010 小时前
探索云原生架构:从容器到微服务的全面升级
微服务·云原生·架构
喵了几个咪10 小时前
Kratos微服务轻松对接EFK日志系统
微服务·云原生·架构
檐下翻书17310 小时前
从入门到精通:流程图制作学习路径规划
论文阅读·人工智能·学习·算法·流程图·论文笔记