Zero to one registry and load balancing of spring cloud

Keywords: Java Spring Spring Boot Spring Cloud

Zero to one registry and load balancing of spring cloud


Friends who know about distributed services must be familiar with zookeeper. It plays the role of a registration center, and then you can register and subscribe to services through Dubbo. Microservices are a collection of distributed products. They also need a registry to register and subscribe to services.

Simply build the spring cloud environment

		// Spring cloud environment is easy to build
		<dependencies>
            <!-- springCloud -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- nacos Management dependency -->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.2.6.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- mysql drive -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
            <!--mybatis-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
        </dependencies>

Eureka of the registry

Eureka, as the spring cloud registry, can register and discover services.
The main process is as follows:

  • After creating an instance of A service, register the information in Eureka server.
  • Eureka server saves the mapping relationship between service name and service address.
  • B service pulls the service list in Eureka server.

Eureka Registry Service Setup

  1. Create a module of Eureka registry to build.
  2. Add = = @ SpringBootApplication = = annotation in the startup class.
  3. Fill in the following configuration file in the springapplication.yml file, indicating Eureka's address, name and port number
	server:
	  port: 10086
	spring:
	  application:
	    name: eurekaserver # eureka's service name
	eureka:
	  client:
	    service-url: # Address information of eureka
	      defaultZone: http://localhost:10086/eureka
  1. Visit localhost:10086 to see if the configuration is successful.

Service registration and discovery

  1. The following dependencies are introduced into the service pom file:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  1. Write configuration file
spring:
  application:
    name: Service name
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka # registry address
  1. If you want to pull and call services, you need to do the following steps:
    First, create a restTemplate and inject it into the spring container to make service calls through its api to send requests.
    Then call the service in the service layer.
   @Bean
    @LoadBalanced // load balancing 
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
  

	//  service layer
	@Autowired
    private RestTemplate restTemplate;

    public Order queryOrderById(Long orderId) {
        // 1. Query order
        Order order = orderMapper.findById(orderId);
        // 2. Use RestTemplate to send http request and query users
        // 2.1 url
        String url = "http://userservice/user/"+order.getUserId();
        // 2.2 send http request to realize remote call
        User user = restTemplate.getForObject(url, User.class);
        // 3. Encapsulate user to order
        order.setUser(user);
        // 4. Return
        return order;
    }

load balancing

Spring cloud has built-in Ribbon for load balancing configuration, which can be modified by configuring different load balancing strategies.
There are three main load balancing strategies:

  • polling
  • random
  • weight

Custom load balancing

By defining IRule, you can modify load balancing rules in two ways:

  1. Create a load balancing policy Bean through code and add = = @ LoadBalanced = = annotation in front of the Bean instance of RestTemplate. This method implements the load balancing policy of this method for all services.
	@Bean
	public IRule randomRule(){
	    return new RandomRule();
	}
  1. Configure in the configuration file.
serviceName: # Configure load balancing rules for a micro service. serviceName refers to the service name
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # Load balancing rules 

Turn on hungry loading

Because the Ribbon is lazy by default, that is, it is created only when called. When the user calls it for the first time, the Ribbon needs to be loaded very slowly, so hungry loading is used, that is, it is loaded during initialization.

ribbon:
  eager-load:
    enabled: true
    clients: userservice

Nacos of the registry

Add dependency in parent project:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-alibaba-dependencies</artifactId>
    <version>2.2.6.RELEASE</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>

Add dependencies to each service:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

Service hierarchical storage model

The service hierarchical storage model I understand is that Nacos manages service diversity groups; The main purpose is disaster recovery.
Service hierarchical storage model is service - > Cluster - > instance; Call and manage services through these three levels, and call service instances in the same / different clusters depending on the situation.

Configure service cluster

spring:
  cloud:
    nacos:
      server-addr: localhost:8848
      discovery:
        cluster-name: HZ # Cluster name

Modify load balancing

In addition, since the default load balancing policy cannot give priority to the same cluster for load balancing, it is necessary to modify the load balancing policy:

serviceName:
  ribbon:
    NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule # Load balancing rules

Environmental isolation

Nacos provides a namespace for environment isolation.

  • There can be multiple namespace s in a nacos
  • There can be group s, service s, etc. in the namespace
  • Different namespaces are isolated from each other. For example, services in different namespaces are not visible to each other

Configuring a namespace for a microservice can only be achieved by modifying the configuration:

spring:
  cloud:
    nacos:
      server-addr: localhost:8848
      discovery:
        cluster-name: HZ
        namespace: 492a7d5d-237b-46a1-a99a-fa8e98e4b0f9 # Namespace, fill in ID

The difference between Eureka and Nacos

Similarities between Nacos and Eureka:

  • Heartbeat is used for health detection
  • You can register and discover services

The difference between Nacos and Eureka:

  • Nacos supports the server to actively detect the provider status: the temporary instance adopts the heartbeat mode, and the non temporary instance adopts the active detection mode
  • Temporary instances with abnormal heartbeat will be rejected, and non temporary instances will not be rejected
  • Nacos supports the message push mode of service list change, and the service list is updated more timely

Posted by barrywood on Fri, 15 Oct 2021 10:58:38 -0700