Microservice development framework: introduction to eureka and nacos

Posted by garblar on Fri, 18 Feb 2022 16:35:58 +0100

I Microservices

1. Single architecture and distributed architecture

  • Monomer architecture
  • Distributed architecture
    The system is split according to business functions, and each business module is developed as an independent project to become a service
    advantage:
    Disadvantages: the strength of service splitting, how to maintain the address of service cluster, how to realize remote call between services, and how to perceive the health status of services
  • Microservices
    • characteristic:
      • Single responsibility: small efforts to split
      • Service oriented: the business interface exposed by microservices
      • Autonomy: team independence, technology independence, data independence and deployment independence
    • structure
      • Service Cluster
      • Registration Center
      • Configuration center
      • Service gateway
      • Service monitoring and protection
    • frame
      • springcloud
      • Dubbo

2.springcloud

  • 1. Introduction
    • function
      • Service registration discovery
      • Service remote invocation
      • Service link monitoring
      • Unified configuration management
      • Unified Gateway Routing
      • Flow control, degradation and protection
    • springcloud is compatible with the springboot version

II Service splitting and remote invocation

Service splitting

  • Precautions for splitting
    • 1. Do not develop the same business repeatedly for different micro services
    • 2. The microservice data is independent. Do not access the databases of other microservices
    • 3. Microservices can expose their business as interfaces for other microservices to call
  • Split demo
    • 1. Project separation
    • 2. Database separation

Remote call

  • Remote call
    • Requirement: query the order information in the order module and return the user information.
    • step
      • 1) Register RestTemplate

      • 2) Make http requests in OrderService by using the api of template

be careful:
1. When post is requested, the corresponding api is postForObject
2. Both application s should be running

  • Providers and consumers
    • Service provider: a service called by other micro services in a business.
    • Service consumers: services that call other micro services in one business.

III Eureka registry

eureka registration

  • eureka role
    • Eureka server registry: save the address information and heartbeat monitoring of the client
    • Eureka client client:
      • Provider: register your own information, send heartbeat
      • Consumer: pull service list information and issue remote call
  • effect
    • Provide provider information
      The provider registers its own information with eureka at startup
      eureka save information
      Consumers pull provider information from eureka according to the service name
    • The consumer selects an appropriate provider from multiple providers
      Using the load balancing algorithm, select one from the service list
    • Help consumers perceive the health status of providers
      The provider sends heartbeat request to Eureka server every 30 seconds to report the health status
      eureka updates and records the service list information. If the heartbeat is normal, it will not be rejected
      Consumers get the latest information
  • Hands on practice
    • 1. Set up a registration center: register EurekaServer

      <dependency>
          <groupId>org.springframework.cloud</groupId>
         <!-- Don't make a mistake, otherwise yml The file is not recognized-->
          <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
      </dependency>
      
      @EnableEurekaServer
      @SpringBootApplication
      public class EurekaApplication {
      public static void main(String[] args) {
      		SpringApplication.run(EurekaApplication.class,args);
      	}
      }
      
      server:
        port: 10086
      spring:
        application:
      	  name: eurecaserver
      eureka:
        client:
      	register-with-eureka: false   #Register yourself in eureka
      	fetch-registry: false         #Get information from eureka
        service-url:
      	defaultZone: http://127.0.0.1:10086/eureka/
      
    • 2. Registration service: register user service and order service with Eureka

      <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
      </dependency>
      
      spring:
        application:
          name: orderservice
       eureka:
      	client:
      	  service-url:
      		defaultZone: http://127.0.0.1:10086/eureka/
      
      
    • 3. Service discovery: pull the service in order service, and then select a service through load balancing to realize remote invocation

      @MapperScan("cn.itcast.order.mapper")
      @SpringBootApplication
      public class OrderApplication {
      
      	public static void main(String[] args) {
      		SpringApplication.run(OrderApplication.class, args);
      	 }
      	@Bean
      	@LoadBalanced
      	public RestTemplate restTemplate(){return new RestTemplate();}
      }
      
      @Service
      public class OrderService {
      
          @Autowired
          private OrderMapper orderMapper;
          @Autowired
          private RestTemplate restTemplate;
      
          public Order queryOrderById(Long orderId) {
              // 1. Query order
              Order order = orderMapper.findById(orderId);
              // 2. Use resttemplate to send an http request to query the user
              String url = "http://userservice/user/" + order.getUserId();
              User user = restTemplate.getForObject(url, User.class);
              // 3. Encapsulate user for order
              order.setUser(user);
              // 4. Return
              return order;
          }
      }
      

Ribbon load balancing

  • Ribbon load balancing
    -Principle
    -The rule interface is IRule
    -The default implementation is ZoneAvoidanceRule. Select the service list according to the zone, and then poll

  • Load balancing strategy

    • Change load balancing strategy

      • 1. Code method: define a new IRule in the OrderApplication class in order service: (scope: all services)

        @Bean
        public IRule randomRule(){   
        	return new RandomRule();
        }
        
      • 2. Configuration file method: in the application. Of order service In the YML file, you can add a new configuration or modify the rules (only for a service)

      	userservice:
      	  ribbon:
      	    NFLoadBalancerRuleClassName:  com.netflix.loadbalancer.RandomRule# 
      
    • Starvation loading

      • By default, the Ribbon uses lazy loading, that is, the LoadBalanceClient will be created when it is accessed for the first time, and the request time will be very long. Hungry loading will be created when the project starts, reducing the time-consuming of the first visit
      • Configure hungry loading:
        ribbon:
          eager-load:
            enabled: true # Turn on hungry loading   
            clients: userservice # Specifies to load the userservice
        
        

IV Nacos registry

4.1. Understanding and installing nacos

  • Nacos: it is a product of Alibaba and is now a component of spring cloud. Compared with Eureka, it has more functions and is more popular in China
  • Installation:
    • Default port: 8848
    • Start: enter the bin directory of the installation path - > execute the command: startup cmd -m standalone
    • Login: the default account password is nacos

4.2. nacos quick start (Registration)

  • nacos registry

  • Note: start nacos first; Then the application of order – service and userservice can be started successfully, otherwise an error will be reported

            <!--nacos Management dependency-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.2.5.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
    
       <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
    
    spring:
      cloud:
        nacos:
          server-addr: localhost:8848 #nacos server address
    

4.3. nacos service hierarchical storage model and NacosRule load balancing

  • Hierarchical storage model
    • The first level is services, such as userservice
    • The second level is the cluster, such as Hangzhou or Shanghai
    • The third level is the instance, for example, a server deployed with userservice in Hangzhou computer room
  • colony
    • Concept: similar to grouping in the name of place names
    • Set the cluster attribute of the instance: configure the cluster for userservice
      Modify the application. Of userservie yml:
      spring:  
        cloud:
          nacos:
            server-addr: localhost:8848 # nacos server address     
            discovery:
              cluster-name: HZ # Configure the cluster name, that is, the location of the machine room, for example: HZ, Hangzhou
      
      View changes in the ConAs console:
  • NacosRule load balancing
    • Set up NacosRule load balancing
      In the application of consumer orderservice Set the IRule of load balancing in the YML file to NacosRule

      userservice:
        ribbon:
        		NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule # Load balancing rules 
      
    • NacosRule gives priority to the load balancing feature of the same cluster

      • Give priority to the list of service instances in the same cluster
      • If the local cluster cannot find the provider, it will access across the cluster and issue a warning
      • After determining the list of available instances, random load balancing is used to select instances
  • Load balancing according to weight
    • Weight control of instances
      1) The Nacos console can set the weight value of an instance between 0 and 1
      2) For multiple instances in the same cluster, the higher the weight, the higher the frequency of access
      3) If the weight is set to 0, it will not be accessed at all
    • Set the weight value of the instance:

4.4. nacos environmental isolation

  • Environment isolation namespace: the outermost layer of service storage and data storage in Nacos is called namespace, which is used for outermost isolation

    • characteristic:
      1) Each namespace has a unique id
      2) When setting the namespace for a service, write the id instead of the name
      3) Services in different namespace s are not visible to each other
  • Add namespace:

  • Add a namespace for the order service service
    Modify the application of order service YML, add the id of the namespace

    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/heima?useSSL=false
          username: root
          password: 123
          driver-class-name: com.mysql.jdbc.Driver
          cloud:
            nacos:
              server-addr: localhost:8848
              discovery:
                cluster-name: SH # Shanghai
                namespace: 492a7d5d-237b-46a1-a99a-fa8e98e4b0f9 # Namespace, fill in ID
    
    

    Then restart the order service and view the console

V Nacos VS Eureka

5.1 differences

  • What Nacos and eureka have in common
    Both support service registration and service pull
    All support service providers to do health detection by heartbeat
  • The difference between Nacos and Eureka
    1) 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
    2) Nacos supports the message push mode of service list change, and the service list is updated more timely
    3) Nacos cluster adopts AP mode by default. When there are non temporary instances in the cluster, CP mode is adopted; Eureka adopts AP mode

5.2 temporary and non temporary cases

  • Temporary and non temporary instances
    • When registering a service with Nacos: you can choose to register as a temporary or non temporary instance. The default is a temporary instance

    • Configure non temporary instances
      In the application of the service In YML:

      spring:
        cloud:
      	nacos:
        	  discovery:
          	ephemeral: false # Set to non temporary instance
      
    • Difference: (temporary instance recommended)
      1) The temporary instance adopts heartbeat mode, and the non temporary instance adopts active detection mode
      2) When the temporary instance goes down, it will be removed from the service list of nacos, while the non temporary instance will not

Topics: Spring Cloud Microservices eureka