Spring Cloud Alibaba Basics Tutorial: Using Nacos to register and discover services, we have learned how to use Nacos to register and discover services, and also introduced how to obtain specific instances of a service through the LoadBalancerClient interface, and initiate service interface consumption requests based on the instance information. However, this approach requires us to manually write service selection, link splicing and other tedious work, which is very unfriendly to developers. So let’s take a look at what other ways of consuming services are supported.

Use RestTemplate

In the previous example, the RestTemplate has been used to make HTTP requests to a specific instance of the service, but the specific request path is done through concatenation, which is not good for the development experience. In fact, however, RestTemplate has been enhanced in Spring Cloud to simplify the previous invocation with a little configuration.

Such as:

@EnableDiscoveryClient
@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    @Slf4j
    @RestController
    static class TestController {

        @Autowired
        RestTemplate restTemplate;

        @GetMapping("/test")
        public String test() {
            String result = restTemplate.getForObject("http://alibaba-nacos-discovery-server/hello?name=didi", String.class);
            return "Return : " + result;
        }
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

}
Copy the code

As you can see, the @loadBalanced annotation is added to define the RestTemplate. When the service interface is called, the host part is manually concatenated with the IP and port, and the request path is written using the service name. When the actual call is made, Spring Cloud intercepts the request, selects the node through the load balancer, and replaces the service name part with a specific IP address and port, thus realizing the load balancing call based on the service name.

For this approach, see the complete code sample in the end warehouse. For the implementation principle of this approach, you can refer to the first half of this article I wrote earlier: Spring Cloud source analysis (ii) Ribbon

Using WebClient

WebClient is a recent addition to Spring 5 and can be thought of as a Reactive version of the RestTemplate. Here’s a concrete example that will implement the same request invocation as the RestTemplate above:

@EnableDiscoveryClient
@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    @Slf4j
    @RestController
    static class TestController {

        @Autowired
        private WebClient.Builder webClientBuilder;

        @GetMapping("/test")
        public Mono<String> test() {
            Mono<String> result = webClientBuilder.build()
                    .get()
                    .uri("http://alibaba-nacos-discovery-server/hello?name=didi")
                    .retrieve()
                    .bodyToMono(String.class);
            return result;
        }
    }

    @Bean
    @LoadBalanced
    public WebClient.Builder loadBalancedWebClientBuilder() {
        return WebClient.builder();
    }

}
Copy the code

As you can see, the @loadBalanced annotation was added to the WebClient.Builder definition, just like the RestTemplate annotation. A complete example of WebClient can also be found in the repository at the end of this article.

Use Feign

The RestTemplate and WebClient tools described above are packaged by Spring itself. Here is a member of Netflix OSS that makes it easier to define and use a service consumption client. Here is a concrete example that implements the same results as the above two methods:

Step 1: Add openFeign dependencies to POM.xml:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
Copy the code

Step 2: Define and use the Feign client:

@EnableDiscoveryClient @SpringBootApplication @EnableFeignClients public class TestApplication { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } @Slf4j @RestController static class TestController { @Autowired Client client; @GetMapping("/test") public String test() { String result = client.hello("didi"); return "Return : " + result; } } @FeignClient("alibaba-nacos-discovery-server") interface Client { @GetMapping("/hello") String hello(@RequestParam(name = "name") String name); }}Copy the code

The @enableFeignClients annotation is used to enable the Spring Cloud Feign client scanning function. Then create a Feign client interface definition. Use the @FeignClient annotation to specify the name of the service to be invoked by this interface. Functions defined in the interface can bind to the REST interface of the service provider using the Spring MVC annotation. For example, here is an example of the/Hello interface bound to the Alibaba-nacos-discovery-server service. Finally, in the Controller, the implementation of the Client interface is injected and the Hello method is called to trigger a call to the service provider. A complete example of using Feign can also be found in the repository at the end of this article.

Deep thinking

Readers who have used Spring Cloud before will feel that whether I use RestTempalte, WebClient, or Feign doesn’t really matter whether I use Nacos or not. We used the same approach to service calls when we introduced Eureka and Consul earlier, didn’t we?

Indeed, for Spring Cloud veterans, even if we switched to Nacos as the new service registry, there would be no impact on our application-level code. So why does Spring Cloud provide such a perfect coding experience? In fact, this is entirely due to the encapsulation of Spring Cloud Common, which abstracts service registration and discovery, client load balancing, and so on, while the upper level applications rely on these abstract interfaces rather than the implementation of a specific middleware. So, in Spring Cloud, we can easily switch middleware for service governance.

Code sample

The sample reader of this article can view the following repository:

Examples of this article can be seen in the following items:

  • alibaba-nacos-discovery-server: service provider that must be started
  • alibaba-nacos-discovery-client-resttemplate: Consume with RestTemplate
  • alibaba-nacos-discovery-client-webclient: Use WebClient to consume
  • alibaba-nacos-discovery-client-feign: Consume with Feign

If you are interested in these, welcome to star, follow, favorites, forward to give support!

The following tutorials may be of interest to you