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

相关推荐
wuxinyan1231 小时前
大模型学习之路03:提示工程从入门到精通(第三篇)
人工智能·python·学习
十安_数学好题速析2 小时前
【多选】曲线方程:四步避坑判断曲线类型
笔记·学习·高考
千寻girling2 小时前
五一劳动节快乐 [特殊字符][特殊字符][特殊字符]
java·c++·git·python·学习·github·php
波特率1152003 小时前
git指令学习
git·学习
eLIN TECE3 小时前
Golang 构建学习
开发语言·学习·golang
chase。4 小时前
【学习笔记】skrl: 模块化、灵活的强化学习库深度解析
笔记·学习
亚历克斯神4 小时前
Java 安全最佳实践:构建安全的 Java 应用
java·spring·微服务
nashane4 小时前
HarmonyOS 6学习:HAR包与HSP包的选择与优化指南
学习·华为·harmonyos·harmonyos 5
MegaDataFlowers4 小时前
英语六级我还在背单词:Unit 1(Lesson 1)
学习
maaath5 小时前
【maaath】Flutter for OpenHarmony 学习答题应用实战开发
学习·flutter·华为·harmonyos