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

相关推荐
red_redemption22 分钟前
自由学习记录(211)
学习
ThsPool1 小时前
【ENVI二次开发学习整理 02】IDL语言基础与程序设计
学习·中间件
confiself1 小时前
树形思考研究进展
java·大数据·微服务
一只小菜鸡..2 小时前
南京大学 操作系统 (JYY) 学习笔记:文件系统实现——从 FAT、ext2 到现代 B-Tree 黑科技
笔记·科技·学习
深爱水瓶 血影S狂风2 小时前
Linux.NET学习手记(2)
linux·学习·.net
明明真系叻2 小时前
RAG学习(1)
学习·rag
✎ ﹏梦醒͜ღ҉繁华落℘2 小时前
单片机基础知识--LVGL学习-lv_obj_add_flag()
c语言·单片机·学习
春水碧于天,画船听雨眠2 小时前
LangChain学习笔记(一)
笔记·学习·langchain
zerwave2 小时前
Docker 学习:多容器网络互通——从 host 模式到自定义 bridge 网络
网络·学习·docker
Zzj_tju2 小时前
Instruction Tuning 论文精读路线:从 Supervised Fine-Tuning 到 Instruction Following
人工智能·笔记·学习·语言模型·自然语言处理