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

相关推荐
程序员夏洛6 分钟前
HTTP 2.0 和 3.0 有什么区别?
网络·网络协议·http
是隼人10 分钟前
buuctf-pwn PWN4(双引号的转义缺陷)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
蒸蒸yyyyzwd13 分钟前
CPP选手秋招准备学习笔记day25
笔记·学习
小白说大模型21 分钟前
Hermes 全配置指南:从裸版到 AI Agent 天花板
大数据·人工智能·学习·算法·机器学习·数据挖掘
m4Rk_44 分钟前
【论文阅读】Agent 记忆机制(60):MemInsight——让 LLM 自动为历史记忆生成语义索引
论文阅读·人工智能·学习·开源·github
小弥儿6 小时前
开源 VoiceStudio,声音克隆|配音|有声书一站式本地完成
学习·开源·github
点心的游戏开发世界8 小时前
Unity C# 脚本学习笔记:命名空间与 using
学习·unity·c#
香芋芋圆10 小时前
AI 冲击内卷之下,普通前端如何破局?WebGIS—— 低门槛突围赛道
前端·javascript·人工智能·学习·职场发展
点心的游戏开发世界10 小时前
Unity C# 脚本学习笔记:泛型
学习·unity·c#
tju新生代魔迷11 小时前
Verilog HDL 学习笔记(十三)| 第13章 编程语言接口(PLI)
笔记·学习