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

相关推荐
闫记康几秒前
Linux学习day4
linux·运维·学习
00后程序员张7 分钟前
HTTPS单向认证、双向认证、抓包原理与反抓包策略详解
网络协议·http·ios·小程序·https·uni-app·iphone
南境十里·墨染春水13 分钟前
线程池学习(四) 实现缓存式线程池
学习
吃好睡好便好42 分钟前
伽利略·伽利雷的故事
学习
GEO从入门到精通42 分钟前
为什么要学习GEO?
人工智能·学习
June bug1 小时前
Failed to fetch+HTTP 422=Agent ID 不匹配
网络·网络协议·http
星幻元宇VR1 小时前
VR消防安全体验屋|沉浸式科技助力消防安全科普
人工智能·科技·学习·安全·vr
小+不通文墨2 小时前
在树莓派中部署emqx
经验分享·笔记·单片机·学习
玄米乌龙茶1232 小时前
LLM 应用开发学习笔记:System Prompt 设计、注入风险与成本优化
笔记·学习·prompt
爱喝水的鱼丶2 小时前
SAP-ABAP:数据类型与数据对象(8篇) 第四篇:关系映射篇——从类型定义到对象实例的转化逻辑
开发语言·数据库·学习·sap·abap