The commonly used methods for calling microservices to each other are
HttpUrlConnection or classic network access framework HttpClient
However, in the Spring project, using RestTemplate is clearly more convenient
RestTemplate
Introduction:
RestTemplate is an HTTP request tool supported since Spring 3.0, which provides templates for common REST request schemes, such as GET requests, POST requests, PUT requests, DELETE requests, and some common request execution methods such as exchange and execute. The RestTemplate inherits from InterceptingHttpAccessor and implements the RestOperations interface, which defines basic RESTful operations that are implemented in the RestTemplate.
usage
GET request
1.getForEntity
1 | @RestController |
The first parameter is the URL, which has a placeholder {1}. If there are multiple placeholders represented by {2}, {3}…, the second parameter is the data type returned by the interface, and finally, a variable length parameter is used to fill in values for the placeholder.
Two other parameter formats
- Placeholders do not use numbers, but instead use the key of the parameter, while placing the parameter in a map. The key in the map corresponds to the key in the placeholder, and the value in the map is the specific value of the parameter. For example, in the above request, the map is used to pass the parameter, and the request method is as follows:
1
2
3
4Map<String, Object> map = new HashMap<>();
String url = "http://" + host + ":" + port + "/hello?name={name}";
map.put("name", name);
ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, map); - The second option is to use Uri objects. When using Uri objects, parameters can be directly concatenated into addresses, such as the following:2.getForObject
1
2
3String url = "http://" + host + ":" + port + "/hello?name="+ URLEncoder.encode(name,"UTF-8");
URI uri = URI.create(url);
ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);
The method usage is similar to the above, with the only difference being that the return value of getForObject is the data returned by the service provider, and using getForObject cannot obtain the response header.
POST request
1.postForEntity
1 | String url = "http://" + host + ":" + port + "/hello2"; |
The first parameter of the postForEntity method is the request address, the second parameter is the map object, which stores the request parameter key/value, and the third parameter is the returned data type
1 | User u1 = new User(); |
2.postForObject
PostForObject and postForEntity are basically the same, except for different return types, which will not be repeated here.
3.postForLocation
1 | String s = restTemplate.getForObject(uri, String.class); |
PUT request
provider
1 | @PutMapping("/user/name") |
Caller
1 | MultiValueMap map = new LinkedMultiValueMap(); |
DELETE request
provider
1 | @DeleteMapping("/user/{id}") |
Caller
1 | @GetMapping("/hello10") |