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

相关推荐
0566461 小时前
Python高级——迭代器
开发语言·python·学习
math_hongfan1 小时前
鸿蒙Agent高级技能自定义开发:自定义意图服务/能力注册/Agent技能编排/服务插件开发实战
android·学习·华为·harmonyos·鸿蒙
duhong20262 小时前
Linux刷题记录第一套
学习
AI 小老六2 小时前
Agent Runtime 如何用 Session、Memory、User Profile 和 Skill 实现外部学习
服务器·人工智能·学习·ai·架构·自动化
又折桃枝换酒钱2 小时前
CycleChart:一个统一的基于一致性学习的双向图表理解与生成框架(翻译与解读)
人工智能·深度学习·学习
什仙3 小时前
Maxwell:提取实体表面,用于扫掠。
笔记·学习·ansys·maxwell
小僧景贤3 小时前
嵌入式C语言 第十一篇:成长路线|嵌入式C工程师完整进阶学习路径(从零到工程级落地|含周期+实战项目)
c语言·开发语言·学习
DsirNg4 小时前
一文讲清网络协议:从打开网页到理解 HTTP、HTTPS 与 TLS
http·https·dns·网络基础·入门教程·tls·web 安全
奈斯先生Vector4 小时前
2026 AIGC API 网关韧性评测:为什么 HTTP 200 不等于有效交付
网络协议·http·aigc