微服务模块-RestTemplate 用法详解

RestTemplate

RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具,它提供了常见的REST请求方案的模版,例如 GET 请求、POST 请求、PUT 请求、DELETE 请求以及一些通用的请求执行方法 exchange 以及 execute。RestTemplate 继承自 InterceptingHttpAccessor 并且实现了 RestOperations 接口,其中 RestOperations 接口定义了基本的 RESTful 操作,这些操作在 RestTemplate 中都得到了实现。接下来我们就来看看这些操作方法的使用。

使用

1.get方式(查询)

    @Autowired
    RestTemplate restTemplate;


//    @Bean
//    public RestTemplate getRestTemplate(){
//        return new RestTemplate();
//    }

    @Bean
    public RestTemplate getRestTemplate(RestTemplateBuilder builder){
        return builder.build();
    }


    @GetMapping("user")
    public String getWay(){
        return restTemplate.getForObject("http://localhost:8082/order",String.class);//第二个参数是返回值类型
    }

2.post方式(增加)

方法的第一参数表示要调用的服务的地址
方法的第二个参数表示上传的参数
方法的第三个参数表示返回的消息体的数据类型

public String getWay(){
    return restTemplate.postForObject("http://localhost:8082/order","1",String.class);
}

3.PUT请求(修改)

请求方:

public String getWay(){
    User user=new User();
    user.setId(1);
    //user对象是我要提交的参数,最后的10用来替换前面的占位符{1}
     restTemplate.put("http://localhost:8082/order/{1}",user,10);
     return "22";
}

接收方

@PutMapping("/order/{id}")
public void getOrder(@PathVariable int id ,@RequestBody User user){
    System.out.println(id+"-----"+user.getId());
}

4.delete请求(删除)

请求方

public String getWay(){
     //10用来替换前面的占位符{1}
     restTemplate.delete("http://localhost:8082/order/{1}",10);
     return "22";
}

接收方

@DeleteMapping("/order/{id}")
public void getOrder(@PathVariable int id){
    System.out.println(id+"-----");
}

猜你喜欢

转载自blog.csdn.net/weixin_42371621/article/details/115228044