一,RestTemplate的概述
RestTemplate是spring-web-xxx.jar包中提供的http协议实现类,底层封装了HttpClient,在导入spring-boot-starter-web项目可以直接使用RestTemplate
RestTemplate可以使用Http请求,发送请求获取服务,在SpringCloud服务的调用主要使用http所以RestTemplate很好的适应这种方式,在Dubbo中使用PruBuff进行通信和服务调用这一点和SpringCloud有很大区别
RestTemplate主要针对6类请求方式封装方法:
|
HTTP Method
|
RestTemplate Method
|
|
DELETE
|
delete
|
|
GET
|
getForObject 和 getForEntity
|
|
HEAD
|
headForHeaders
|
|
OPTIONS
|
optionsForAllow
|
|
POST
|
postForObject 和 postForEntity
|
|
PUT
|
put
|
|
any
|
exchange 和 execute
|
ForObject和ForEntity的区别:
- ForObject返回值只要响应体内容也就是Object对象
- ForEntity除了响应体还要响应头信息
二,RestTemplate的使用
一, RestTemplate的GET请求
RestTemplate发送get请求的方法有两种:
- getForObject方法:之后返回响应体
- getForEntity方法:返回响应体,响应头,状态码
参数:
- String url:请求URL(必选)
- Class<T> responseType:响应返回体的数据类型(必选)
- Object... uriVariables:可变参数,响应体
- Map<String, ?> uriVariables:map集合,把请求参数放入集合中
getForObject和getForEntity设置请求参数的三种写法:
1,字符串拼接
@RequestMapping("/payment/select/{id}")
public CommonResult<payment> select(@PathVariable("id") int id){
PAYMENT_URL="localhost:9090";
return restTemplate.getForObject(PAYMENT_URL+"/payment/select/"+id,CommonResult.class);
}
2,参数+占位符
@RequestMapping("/payment/select/{id}")
public CommonResult<payment> select(@PathVariable("id") int id){
PAYMENT_URL="localhost:9090";
//{}表示占位符,数字表示第几个参数
return restTemplate.getForObject("{1}/payment/select/{2}",CommonResult.class,PAYMENT_URL,id);
}
3,map集合+占位符
@RequestMapping("/payment/select/{id}")
public CommonResult<payment> select(@PathVariable("id") int id){
PAYMENT_URL="localhost:9090";
Map place = new HashMap();
place.put("url",PAYMENT_URL);
place.put("id",id);
//{}表示占位符,字符为集合中的Key
return restTemplate.getForObject("{url}/payment/select/{id}",CommonResult.class,PAYMENT_URL,place);
}
二, RestTemplate的POST请求
RestTemplate发送Post请求的方法有两个:
- postForObject方法:之后返回响应体
- postForEntity方法:返回响应体,响应头,状态码
参数:
- String url:请求URL
- @Nullable Object request:请求体内容
- Class<T> responseType:响应体类型
- Object... uriVariables:参数
@RequestMapping(value = "/payment/create",method = RequestMethod.GET)
public CommonResult<payment> create(payment payments){
return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payments,CommonResult.class);}
三,Ribbon和RestTemplate结合
在服务的调用中一般使用Ribbon+RestTemplate,前者进行负载均衡后者进行服务调用
SpringBoot中整合非常简单:在RestTemplate配置中加一个@LoadBalanced注解
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced//这个注解由Ribbon提供
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}





Comments | NOTHING