Rest Template 使用

大家好我是苏麟 今天带来Rest Template .

spring框架中可以用restTemplate来发送http连接请求, 优点就是方便.

Rest Template 使用

Rest Template 使用步骤

java 复制代码
    /**
     * RestTemple:
     * 1.创建RestTemple类并交给IOC容器管理
     * 2. 发送http请求的类
     */

1.注册RestTemplate对象

java 复制代码
@SpringBootApplication
public class OrderApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }


    /**
     * 创建RestTemple类并交给IOC容器管理
     *
     * @RestTemple 是发送http请求的类
     *
     * @LoadBalanced 负载均衡注解
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

2.发送HTTP请求

java 复制代码
@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    //引入
    @Autowired
    private RestTemplate restTemplate;


    public Order queryOrderById(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);

        //2.利用RestTemplate发起http请求,查询用户信息
        //2.1 url
        String url = "http://userserver/user/" + order.getUserId();

        //2.2 发送http请求,实现远程调用
        User u = restTemplate.getForObject(url, User.class);

        //3.封装到order里
        order.setUser(u);

        // 4.返回
        return order;
    }
}

主要代码就是

java 复制代码
        //2.利用RestTemplate发起http请求,查询用户信息
        //2.1 url
        String url = "http://userserver/user/" + order.getUserId();

        //2.2 发送http请求,实现远程调用
        restTemplate.getForObject(url, User.class);

发送Get请求用 getForObject

参数: 第一个参数: 发送请求的路径 , 第二个参数 : 返回的类型

发送Post请求 postForObject

参数: 第一个参数: 发送请求的路径 , 第二个参数 : 请求数据对象 , 第三个参数 : 返回的类型

这期就到这里下期见!

相关推荐
亚历克斯神5 分钟前
智能搜索系统的升级复盘——从 Elasticsearch 到混合检索的检索质量提升
java·spring·微服务
金銀銅鐵1 小时前
[Java] 一个方法最多可以有多少个入参?
java·jvm
哭哭啼1 小时前
JAVA服务问题诊断
java·开发语言·jvm
Sayuanni%32 小时前
SpringBoot 从注解到源码:核心知识点总结
java·spring boot·后端
坚定信念,勇往无前2 小时前
Maven 私有仓库-nexus
java
Minner-Scrapy2 小时前
Scrapy 2.17 源码解析:Scheduler 调度器与磁盘/内存双队列
java·爬虫·python·scrapy·网络爬虫·twisted
晚风醉蝶2 小时前
1-11-奇偶排序-OddEvenSort
java·数据结构·算法
夏天拐跑了西瓜3 小时前
Spring Cloud 微服务实战(三):一个服务挂了,凭什么拖垮整个系统?Sentinel 限流熔断实战
java·spring cloud·微服务
2601_967264283 小时前
Jetpack Compose 实践指南:从入门到进阶
java·学习
m0_587383004 小时前
社区家政系统开发实战:从需求分析到上线部署全指南
java·spring boot·spring·需求分析