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

相关推荐
零域码客5 分钟前
零基础Python爬虫入门:从HTTP协议到 requests + BeautifulSoup 实战
爬虫·python·http
kkkkkkkkkk_Z8 分钟前
新手自学嵌入式 | 学习日记:ARM架构初探与基础概念梳理
arm开发·学习·架构
鬓戈23 分钟前
开源中文输入法技术调研与自建方案
学习·开源
only-lucky1 小时前
QML深入学习七(MVC模块)
学习·mvc
被摘下的星星1 小时前
HTTP 状态码 和 网络端口号
网络·网络协议·http
2401_850122041 小时前
高温耐油热缩套管选型:材料、温度和油液要匹配
经验分享·笔记·科技·学习
Xudde.2 小时前
Me and My Girlfriend 靶机渗透测试(Vulnhub Writeup)
笔记·学习·安全·web安全
Canmag 兴隆磁性2 小时前
自动装盒设备 AO-WCMF
学习·永磁材料·充磁
imDwAaY2 小时前
Bean的生命周期
java·笔记·后端·学习·spring·dubbo
坤坤子吖2 小时前
C++11——Lambda、function、bind 与可调用对象
c++·笔记·学习