In the microservice architecture, calls between services are indispensable. Spring Boot provides developers with a variety of ways to achieve this task, and this article will introduce you in detail.
1. Use RestTemplate
RestTemplate
It is a commonly used REST client in early Spring Boot versions, although in the new Spring version,RestTemplate
It has been marked as not recommended, but it is still necessary to understand its usage. Here's how to use itRestTemplate
Example of making GET and POST requests.
Sample code
import ; import ; import ; import ; // REST GET requestRestTemplate restTemplate = new RestTemplate(); String resultGet = ("/endpoint", ); // REST POST requestHttpHeaders headers = new HttpHeaders(); ("Custom-Header", "Custom header value"); HttpEntity<String> entity = new HttpEntity<>(headers); String resultPost = ("/endpoint", entity, );
2. Use WebClient
WebClient
Is it launched in Spring 5 for alternativesRestTemplate
The new non-blocking REST client.
Sample code
import ; // Create a WebClientWebClient webClient = (""); // REST GET requestString resultGet = () .uri("/endpoint") .retrieve() .bodyToMono() .block(); // REST POST requestString resultPost = () .uri("/endpoint") .header("Custom-Header", "Custom header value") .retrieve() .bodyToMono() .block();
3. Use Feign
To simplify calls between microservices, Spring Cloud provides Feign. Feign makes calling from an HTTP client as simple as calling a local method.
Sample code
import ; import ; import ; // Define Feign interface@FeignClient(name = "example-service", url = "") public interface ExampleClient { @GetMapping("/endpoint") String exampleRequest(); } // Call Feign interface@Autowired private ExampleClient exampleClient; public void doSomething() { String result = (); }
Conclusion
The above briefly introduces the three ways Spring Boot calls external interfaces, but in practice, it is necessary to choose based on the specific requirements and actual situation of the project to ensure optimal project orientation and efficiency. For more related Spring Boot calling external interfaces, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!