Spring boot2.0入門(四)-RestTemplateを使用して複数のSpring bootエンジニアリングを通信
12103 ワード
プロジェクトの中で複数のマイクロサービスを創立することがあって、あるいは1つの大きいプロジェクトを複数のマイクロサービスに分割してデカップリングして、各マイクロサービス間の相互呼び出しを容易に完成するために、Springはテンプレート類RestTemplateを与えて、以下にRestTemplateのいくつかの用法を紹介します:1.RestTemplateを使用してGet要求を行い、要求パラメータが少ない
2.RestTemplateを使用してGet要求を行い、要求パラメータが多くかつ可変である
3.RestTemplateを使用してPOST要求を行い、要求パラメータはJSON要求体を使用する
4.RestTemplateを使用してDELETE要求を行い、削除操作を要求する
5.RestTemplateを通常のHTTPインタラクションとして使用
// 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);
}