有时候项目中要建立多个微服务,或者把一个大的项目拆分成多个微服务进行解耦,为了方便完成各个微服务之间相互调用,
Spring给予了模板类RestTemplate,下面介绍一下RestTemplate的几种用法:
1.使用RestTemplate进行Get请求,请求参数较少
//通过用户ID获取用户信息
public User RestTemplateGet(Long id)
{
RestTemplate restTemplate = new RestTemplate();
User user = restTemplate.getForObject("http://localhost:8080/users/{id}", User.class, id);
return user;
}
2.使用RestTemplate进行Get请求,请求参数多且可变
//通过用户的年龄,性别,所在城市获取用户列表
public List<User> RestTemplateGet(int age,int sex,String city)
{
RestTemplate restTemplate = new RestTemplate();
Map<String,Object> params = new HashMap<String,Object>();
params.put("age",20);
params.put("sex",1);
params.put("city","南京");
String url = "http://localhost:8080/users/{age}/{sex}/{city}";
ResponseEntity<List> responseEntity = restTemplate.getForEntity(url, List.class,params);
List<User> users = responseEntity.getBody();
return users;
}
3.使用RestTemplate进行POST请求,请求参数在使用JSON请求体
//使用Post新增用户
public User RestTemplatePost(User user)
{
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<User> request = new HttpEntity<>(user,headers);
RestTemplate restTemplate = new RestTemplate();
User user = restTemplate.postForObject("http://localhost:8080/users", request, User.class);
return user;
}
4.使用RestTemplate进行DELETE请求,请求删除操作
//使用delete删除用户
public void RestTemplateDelete(Long id)
{
RestTemplate restTemplate = new RestTemplate();
restTemplate.delete("http://localhost:8080/users/{id}",id);
}
5.使用RestTemplate当成普通HTTP交互
//当成普通http请求
public void RestTemplateTest()
{
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HashMap<String, String> maps = new HashMap<>();
maps.put("method", "keepAlive");
HttpEntity<Map> request = new HttpEntity<>(maps,headers);
RestTemplate rest = new RestTemplate();
String str = rest.postForObject("http://localhost:8080/Engine", request, String.class);
System.out.println(str);
}