Use of SpringCloud Eureka Registration Center

Eureka is a service discovery framework developed by Netflix . It is a REST- based service and is mainly used to locate middle-tier services running in the AWS domain to achieve load balancing and fail-over of middle-tier services. SpringCloud integrates it in its sub-project spring-cloud-netflix to realize the service discovery function of SpringCloud.

Service governance

Spring Cloud encapsulates the Eureka Netflix developed to implement existing service governance .

In the traditional rpc remote call framework, it is more complicated to manage the dependencies between each service and services. Service governance is required to manage the dependencies between services and services, which can realize service call, load balancing, fault tolerance, etc., and realize services. Discovery and registration.

Service registration and discovery

Eureka adopts the design architecture of CS (Client Server). Eureka Server serves as the server for the service registration function, and it is the service registration center . Other microservices in the system use Eureka's client to connect to the Eureka Server and maintain a heartbeat connection. In this way, system maintainers can use Eureka Server to monitor whether each microservice in the system is operating normally .

In service registration and discovery, there is a registry. When the server starts, will present information on their own servers, services such as mailing address, etc. to do the name of party type registered to the registry. The other party (consumer) uses the alias to obtain the actual communication address from the registry, and then implements a local RPC call. The core design idea of ​​the RPC remote call framework lies in the registry . Because the registry manages a dependency between each service and the service. In the RPC remote framework, there will be a registry (store service address-related confidence).

  • Service registration : Register service information into the registration center.
  • Service discovery : Obtain service information from the registry.
  • The process of service registration and discovery : start the service registration center, the service provider registers their services to the service center (in the form of an alias), and the service consumers use the service alias to go to the registration center to obtain the service information (calling address), and then proceed Remote call. After the service consumer obtains the service information, it will be stored in the local cache (jvm), and the service information will be updated every 30s by default.

Eureka consists of two components: Eureka Server and Eureka Client

  1. Eureka Server provides service registration service

    After each microservice node is started through the configuration, it will be registered in EurekaServer, so that the service registry in EurekaServer will store the information of all available service nodes, and the information of the service nodes can be seen directly in the interface.

  2. Eureka Client accesses through the registry

    Eureka Client is a java client used to simplify the interaction of Eureka Server. The client also has a built-in load balancer that uses a polling load algorithm. After the application is started, a heartbeat will be sent to the Eureka Server (the default period is 30 seconds). If Eureka Server does not receive the heartbeat of a node in multiple heartbeat cycles, EurekaServer will remove the service node from the service registry (90 seconds by default) .

Eureka Server (server) construction steps

  1. Add the maven dependency of Eureka Server

    <!--Eureka 服务端,老版本spring-cloud-starter-eureka-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
    
  2. Add EurekaServer configuration to the configuration file

    server:
      port: 7001
    eureka:
      instance:
        hostname: localhost #服务实例名称
      client:
        #false表示不向注册中心注册自己,因为自己就是注册中心
        register-with-eureka: false
        #false表示自己就是注册中心,不需要去检索服务信息
        fetch-registry: false
        service-url:
          #注册地址
          defaultZone: http://${
          
          eureka.instance.hostname}:${
          
          server.port}/eureka/
    
  3. Add the annotation @EnableEurekaServer to the springboot startup class

    @SpringBootApplication
    @EnableEurekaServer
    public class EurekaServerApplication {
          
          
    
        public static void main(String[] args) {
          
          
            SpringApplication.run(EurekaServerApplication.class,args);
        }
    }
    

Eureka Client (client) construction steps

  1. Add the maven dependency of Eureka Client

    <!--Eureka 客戶端,老版本spring-cloud-starter-eureka-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    
  2. Add EurekaClient configuration to the configuration file

    #服务端口号
    server:
      port: 8001
    
    #服务名称,注册到eureka上的别名
    spring:
      application:
        name: cloud-payment-service 
    
    #eureka client
    eureka:
      client:
        #是否将自己注册进eurekaServer,默认true
        register-with-eureka: true
        #是否从EurekaServer抓取已有的注册信息,默认为true,集群必须为true
        fetchRegistry: true
        service-url:
          #服务注册地址
          defaultZone: http://localhost:7001/eureka
    
  3. Add the annotation @EnableEurekaServer to the springboot startup class

    @SpringBootApplication
    @EnableEurekaClient
    public class PaymentApplication {
          
          
    
        public static void main(String[] args) {
          
          
            SpringApplication.run(PaymentApplication.class,args);
        }
    }
    

Eureka Server cluster

Eureka cluster : Each Eureka service has other Eureka registration information. Register with each other .

Eureka Server cluster : three EurekaServer clusters

  1. Modify the configuration file

    ##############第一个7001##################
    server:
      port: 7001
    eureka:
      instance:
        hostname: eureka1.com  
      client:
        #false表示不向注册中心注册自己,因为自己就是注册中心
        register-with-eureka: false
        #false表示自己就是注册中心,不需要去检索服务信息
        fetch-registry: false
        service-url:
          #注册地址 。多个集群用逗号隔开。这里做的域名映射,不做也可
          defaultZone: http://eureka2.com:7002/eureka/,http://eureka3.com:7003/eureka/
          
    ##############第二个7002##################      
    server:
      port: 7002
    eureka:
      instance:
        hostname: eureka2.com
      client:
        #false表示不向注册中心注册自己,因为自己就是注册中心
        register-with-eureka: true
        #false表示自己就是注册中心,不需要去检索服务信息
        fetch-registry: false
        service-url:
          #eureka集群互相注册,这里是其他注册中心的地址
          defaultZone: http://eureka1.com:7001/eureka/,http://eureka3.com:7003/eureka/
    
    ##############第二个7003##################        
    server:
      port: 7003
    eureka:
      instance:
        hostname: eureka3.com
      client:
        register-with-eureka: false   #false表示不向注册中心注册自己
        fetch-registry: false   #false表示自己端就是注册中心
        service-url:
          defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7001.com:7001/eureka/
    
  2. Three Eurekas are started, and you can see that they are all registered by looking at the management page

Insert picture description here

Eureka Client is registered into the Eureka cluster

  1. Modify the configuration file defaultZone, fill in all Eureka addresses, separated by commas. Start the project to view the service registration is successful, each has

    #eureka client
    eureka:
      client:
        #是否将自己注册进eurekaServer,默认true
        register-with-eureka: true
        #是否从EurekaServer抓取已有的注册信息,默认为true,集群必须为true
        fetchRegistry: true
        service-url:
          #服务注册地址 ,注册进eureka1,eureka2(eureka3省略不写太长了)
          defaultZone: http://eureka1.com:7001/eureka/,http://eureka1.com:7002/eureka/
    

Eureka Client cluster

  1. Start the service provider with the same service name (different calling address) and register to the Eureka registry

    ###################服务提供者1号,8001端口###############################
    server:
      port: 8001 #端口号
    spring:
      application:
        name: cloud-payment-service #服务名称
    #eureka client
    eureka:
      client:
        register-with-eureka: true
        fetchRegistry: true
        service-url:
          #服务注册地址
          defaultZone: http://eureka1.com:7001/eureka/
          
    ###################服务提供者2号,8002端口###############################
    server:
      port: 8002 #端口号
    spring:
      application:
        name: cloud-payment-service #服务名称
    #eureka client
    eureka:
      client:
        register-with-eureka: true
        fetchRegistry: true
        service-url:
          #服务注册地址
          defaultZone: http://eureka1.com:7001/eureka/      
    
  2. Use RestTemplate to call the service, add @LoadBalanced annotation, turn on load balancing, and convert the logical name of the request address service into a specific call address

    @Configuration
    public class ApplicationContextConfig {
          
          
    
        @Bean
        @LoadBalanced
        public RestTemplate restTemplate(){
          
          
            return new RestTemplate();
        }
    }
    
     * 服务调用地址写成服务名称
     */
    private static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE/payment";
    
    @Resource
    private RestTemplate restTemplate;
    
    @GetMapping(value = "/create")
    public BaseResult create(Payment payment){
          
          
        return restTemplate.postForObject(PAYMENT_URL + "/create",payment,BaseResult.class);
    }
    

Service Discovery

Role: Obtain the service information of the registry.

Discovery use

  1. Add annotation @EnableDiscoveryClient to the springboot startup class

    @SpringBootApplication
    @EnableEurekaClient
    @EnableDiscoveryClient //Discovery
    public class PaymentApplication {
          
          
    
        public static void main(String[] args) {
          
          
            SpringApplication.run(PaymentApplication.class,args);
        }
    }
    
  2. Inject DiscoveryClient into the code to output service information

    @GetMapping(value = "discovery")
    public Object discovery(){
          
          
        //获取服务列表
        List<String> list = discoveryClient.getServices();
        list.forEach(System.out::println);
        //根据服务实例名称获取实例
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.forEach(e -> {
          
          
            System.out.println("serviceId="+e.getServiceId()+"\t"+"host="+e.getHost()+
                    "\t"+"port="+e.getPort()+"\t"+"uri="+e.getUri());
        });
        return discoveryClient;
    }
    

Eureka self-protection

Insert picture description here

EMERGENCY! EUREKA MAY BE INCORRECTLY CLAIMING INSTANCES ARE UP WHEN THEY’RE NOT. RENEWALS ARE LESSER THAN THRESHOLD AND HENCE THE INSTANCES ARE NOT BEING EXPIRED JUST TO BE SAFE.

Baidu Translation : Emergency! EUREKA may falsely claim that the instance started without being started. The renewal is less than the threshold, so the instance will not expire for security .

Eureka self-protection theory knowledge

If a certain service is unavailable at a certain time, the service will not be cleared immediately, and the service information will still be saved. In order to prevent the service from actually running normally, but the network with EurekaServer is disconnected, EurekaServer will not remove the service immediately.

By default, if EurekaServer does not receive the heartbeat of a certain microservice instance within a certain period of time . EurekaServer will log out the instance (90s by default). However, when a network partition (delay, freeze, congestion) failure occurs, the microservices and EurrekaServer cannot communicate normally. The above behavior may become very dangerous-because the microservice itself is healthy, this microservice should not be deregistered at this time . Eureka solves this problem through the " self-protection mode "-when the EurekaServer node loses too many clients in a short period of time (partition failure may occur), then this node will enter the self-protection mode.

In the self-protection mode, EurekaServer will protect the information in the service registry and no longer log out any instances.

**It is better to keep the wrong service registration information than to blindly log out any service instances that may be healthy. **AP in the CAP principle.

Prohibit Eureka from self-protection

  1. EurekaServer add configuration A, B

    server:
      port: 7001
    eureka:
      instance:
        hostname: eureka1.com
      client:
        register-with-eureka: false
        fetch-registry: false
        service-url:
          defaultZone: http://eureka1.com:7001/eureka/
      server:
        #(A)关闭自己我保护机制,保证不可用服务被及时剔除,默认true
        enable-self-preservation: false
        #(B)时间改小。单位:毫秒
        eviction-interval-timer-in-ms: 2000
    
  2. Add configuration A and B on EurekaClient

    #eureka client
    eureka:
      client:
        register-with-eureka: true
        fetchRegistry: true
        service-url:
          defaultZone: http://eureka1.com:7001/eureka/
      instance:
        instance-id: payment8001 
        prefer-ip-address: true
        #(A)Eureka客户端向服务端发送心跳的时间间隔 单位秒,默认30秒
        lease-renewal-interval-in-seconds: 1
        #(B)Eureka服务端在收到最后一次心跳后等待时间上线,单位秒(默认90s),超出时将剔除服务
        lease-expiration-duration-in-seconds: 2
    
  3. Test whether the service is removed in time

Eureka 2.0 (Discontinued)

The existing open source work on eureka 2.0 is discontinued. The code base and artifacts that were released as part of the existing repository of work on the 2.x branch is considered use at your own risk.

Eureka 1.x is a core part of Netflix’s service discovery system and is still an active project.

The existing open source work on eureka2.0 has ceased. Code bases and artifacts released as part of the existing working repository on the 2.x branch are considered to be used at your own risk.

eureka1.x is the core part of Netflix's service discovery system and is still an active project.

Guess you like

Origin blog.csdn.net/zhaoqingquanajax/article/details/114499108
Recommended