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

相关推荐
前路不黑暗@4 分钟前
Java项目:Java脚手架项目的地图的POJO
android·java·开发语言·spring boot·学习·spring cloud·maven
wubba lubba dub dub75010 分钟前
第三十七周学习周报
学习
REDcker10 分钟前
HTTP 协议发展详解:从 HTTP/1 到 HTTP/3
网络·网络协议·http
来两个炸鸡腿34 分钟前
【Datawhale组队学习202602】Hello-Agents task04智能体经典范式构建
人工智能·学习·大模型·智能体
承渊政道1 小时前
Linux系统学习【深入剖析Git的原理和使用(下)】
linux·服务器·git·学习·gitee·vim·gitcode
海兰1 小时前
elasticsearch学习之基本概念-向量数据库
数据库·学习·elasticsearch
海兰2 小时前
elasticsearch学习之基本概念-混合搜索
学习·elasticsearch·jenkins
懒惰的bit2 小时前
Python入门学习记录
python·学习
吨吨不打野2 小时前
error: RPC failed; HTTP 400 curl 22 The requested URL returned error: 400
网络协议·http·rpc