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

相关推荐
DLYSB_7 小时前
从监控告警到现场处置:用 HTTP API、Modbus TCP 构建声光语音告警系统
网络协议·tcp/ip·http·报警灯
zjnlswd7 小时前
C#学习笔记4
笔记·学习·c#
minglie17 小时前
在linux环境烧录esp8266
学习
xqqxqxxq8 小时前
AI Agent学习:MCP与工具生态:工具选择的挑战(李博杰《深入理解 AI Agent》4.3观后总结)
人工智能·学习
青山是哪个青山8 小时前
LangChain 学习笔记(九):上下文与记忆
笔记·学习·langchain
KaKa_大王9 小时前
关于秒杀项目的一些理解
java·学习
Z5998178419 小时前
c#软件开发学习笔记--Modbus-TCP/UDP网口通讯
笔记·学习·c#
vHelios10 小时前
【电商项目】商品搜索开发复盘(1):根据需求拆解搜索接口的设计逻辑
java·微服务·es
zyf10441610 小时前
暑期实践日志 Day29:根据修改要求,进行视频字幕添加
学习·计算机网络·剪辑·暑期实践·课题任务
老郑聊AI业财智造10 小时前
TOGAF、DDD与微服务:软件架构的多维透视
spring boot·spring cloud·微服务·金融·架构·软件工程·制造