In the Spring Cloud family, inter-process communication can be done using
OpenFeign. (Of course there are other ways such as message-driven microservices based on messaging middleware or gRPC-based calls).
RestTemplate can be treated as a common HTTP calling tool, and is particularly convenient for calling RESTful-style interfaces, as opposed to other HTTP clients.
However, more convenient than RestTemplate is OpenFeign, through the interface declaration can achieve remote calls, the specific use of these in the previous article, here will not repeat.
Previously, if we wanted to use declarative HTTP calls, we needed to implement them through
OpenFeign, which requires third-party dependencies. Starting with Spring6 (Spring Boot3), Spring itself provides similar functionality through the
@HttpExchange annotation, which also makes it easy to implement declarative HTTP calls. This is one more option for cross-service calls.
First we create a common Spring Boot project called server. This common Spring Boot project only needs to provide a simple test interface, as follows.
This should not be difficult for everyone, so I won’t go into it.
Now suppose I have another service named client, and I want to call the interface provided by the server in the client.
First of all, let’s create the client project. Note that when creating it, we need to add not only Web dependencies, but also Reactive Web, because the underlying
@HttpExchange is based on WebClient, which is provided by Reactive Web.
Once created, we can then declare the Http interface.
These uses are particularly similar to what we commonly use in SpringMVC, such as @RequestMapping and @GetMapping.
@HttpExchangeis similar to
@RequestMappingin that it can be placed on a class to play a request narrowing role, or on a method, where we can specify the specific request method via the
methodattribute, which is also similar to
@ HttpExchange(value = "/server",method = "GET").
@GetExchangeis similar to
@GetMapping, and this will not be repeated. Other similar annotations are
- Another thing to note is that the request method parameters need to be annotated with
@RequestParam, which is similar to
Once the interface is declared, we still need to configure it to use it. As follows.
This configuration is mainly twofold.
@HttpExchangeis based on WebClient, so we first need to configure WebClient, configure WebClient, also incidentally configure the specific address of the request (because in the
@HttpExchangeannotation does not specify the specific domain name port of the request or something); at the same time, for HTTP requests headers and so on, if you need to customize, is also through the configuration of WebClient to achieve.
- Since the ToDoService we provided earlier is an interface, we also need to provide an implementation class for that interface.
Once all the configuration is done, we can then directly inject the
ToDoService instance wherever we need to use it, as follows.