di inject LoadBalancerClient class to realize load balancing, and use @ LoadBalanced annotation to realize load balancing of RestTemplate

Consumer service discovery and invocation

1. Import dependency

		<dependencies>
    <!-- Web service-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--Registration and discovery of services(We're going to talk about service registration nacos)-->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    </dependencies>

2. Modify yml folder

server:
  port: 8090
spring:
  application:
    name: mu-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Where to find the service

3. Create consumer services

@SpringBootApplication
public class ConsumerApp {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApp.class, args);
    }
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }//Give the RestTemplate object to the spring container for management, so that new can only be called once when it is used
    @RestController
    public class ConsumerController{
        @Value("${spring.application.name:mu}")
        private String appName;
        @Autowired
        private RestTemplate restTemplate;
        @GetMapping("/consumer/doRestEcho1")
        public String doRestEcho01(){
            String url = "http://localhost:8081/provider/echo/"+appName;
            return restTemplate.getForObject(url, String.class);
        }
    }
}

4. Start the consumer service and enter in the browser http://localhost:8090/consumer/doRestEcho1 Address. If the access is successful, it will appear, as shown in the figure:

Design and implementation of service load balancing

1. Modify the ConsumerController class, inject the LoadBalancerClient object, add the doRestEcho2 method, and then access the service

  @Autowired
  private LoadBalancerClient loadBalancerClient;
   
  @GetMapping("/consumer/doRestEcho02")
 public String doRestEcho02(){
     ServiceInstance serviceInstance = loadBalancerClient.choose("mu-provider");
     String url = String.format("http://%s:%s/provider/echo/%s",serviceInstance.getHost(),serviceInstance.getPort(),appName);
     System.out.println("request url:"+url);
     return restTemplate.getForObject(url, String.class);
     }
 }

2. Modify the port number of the yml file in the provider, start multiple provider services, and simulate load balancing. If it is started successfully, the
3. Repeated visits

http://localhost:8090/consumer/doRestEcho02

Here, multiple instances provide services concurrently by load balancing. The default implementation of load balancing here is because Nacos integrates the ribbon. The ribbon and RestTemplate can easily access services. Ribbon is one of the core components of Spring Cloud. The most important function it provides is the load balancing of the client (the client can adopt certain algorithms, such as polling access and accessing the instance information of the server). This function allows us to easily automatically convert the service-oriented REST template requests into service calls in the client load balancing mode.

@LoadBalanced

When using RestTemplate for remote service calls, if load balancing is required, you can use @ LoadBalanced to modify the method of building RestTemplate when building RestTemplate object, such as building RestTemplate object in ConsumerApplication:

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

Perform dependency injection where RestTemplate is required to implement load balancing calls. For example, add the restTemplateloadBalancerClient property in the ConsumerController class

@Autowired
private RestTemplate restTemplateloadBalancerClient;

You can call with the help of the server name based on RestTemplate in the method of the corresponding service caller

        @Autowired
        private RestTemplate restTemplateloadBalancerClient;
        @GetMapping("/consumer/doRestEch03")
        public String doRestEcho03(){
            String url=String.format("http://%s/provider/echo/%s","mu-provider",appName);
            //Send an http request to the service provider to obtain the response data
            return restTemplateloadBalancerClient.getForObject(
                    url,//The address of the service to request
                    String.class);//String.class is the response result type of the requested service
        }

@The LoadBalanced annotation belongs to Spring, not the Ribbon. When Spring initializes the container, if it detects that the Bean is @ LoadBalanced annotated, Spring will set the interceptor of loadbalancerinceptor for it.

Section interview analysis

  • @What is the function of bean annotation? (it is generally used to configure the interior of a class and describe relevant methods. It is used to tell spring that the return value of this method should be managed by spring. The bean name is the method name by default. If you need to specify the name, you can @ Bean("bean name"). The most common application scenario is to integrate third-party resources - objects)
  • @What is the role of Autowired annotations? (this annotation is used to describe attributes, construction methods, set methods, etc. it is used to tell the spring framework to perform DI operations for attributes according to certain rules. By default, the corresponding object is found according to the attribute and method parameter types. If only one is found, it will be injected directly. When there are multiple types, it will also be injected according to the attribute name or method parameter name. If the names are also different, an error will be reported.)
  • How is the bottom layer responsible for balancing in Nacos implemented? (through the Ribbon implementation, some load balancing algorithms are defined in the Ribbon, and then an instance is obtained from the service instance based on these algorithms to provide services for the consumption method)
  • What is Ribbon? (the load balancing client provided by Netflix is generally applied to the service consumption method)
  • What problems can Ribbon solve? (service invocation is based on load balancing policy, and all policies will implement IRule interface)
  • What are the built-in load policies of Ribbon? (8, which can be analyzed by viewing the implementation class of IRule interface)
  • @What is the role of LoadBalanced? (describe the RestTemplate object, which is used to tell the Spring framework that when a service call is made using RestTempalte, the call process will be intercepted by an interceptor, and then start the load balancing policy inside the interceptor.)
  • Can we define our own load balancing strategy? (policy can be defined based on IRule interface or implemented with reference to NacosRule)

Keywords: Java Spring

Added by lorenzo-s on Thu, 16 Sep 2021 23:51:34 +0300