[Spring Cloud] In-depth understanding of the principles of Eureka registration center, service registration and discovery


Preface

In the microservice architecture, service registration and discovery are crucial. To achieve this goal, the Eureka registry came into being. In this article, we will have an in-depth understanding of the principles of the Eureka registry and explore the service registration and discovery mechanism.

In the collaboration of microservices, remote calls between services are a common requirement. However, there are some problems in using the traditional RestTemplate remote calling method, such as high coupling and difficulty in maintenance. In order to solve these problems, we will explore how to use the Eureka registry to elegantly register and discover services, so as to better build a microservice architecture.

Next, we will gradually explore in depth the principles of the Eureka registration center, building Eureka services, service registration and discovery and other key contents. I hope that reading this article can help us more fully understand the role of Eureka in microservice architecture and how to flexibly use it to build an efficient and reliable distributed system.

1. Problems arising from microservice calls

In a microservice architecture, remote calls between services are a common requirement. However, as the complexity of the system increases, service invocation also brings some problems and challenges.

1.1 How do service consumers obtain the address information of service providers?

In a microservice architecture, the address information of service providers is usually dynamic and may change at any time, such as service expansion, shrinkage, migration, etc. Therefore, service consumers need a mechanism to obtain the address information of the service provider to ensure that remote calls can be initiated correctly.

Solution: Service Registration and Discovery

  • The service provider registers its address information to the service registration center when starting, including host name, port number and other information.
  • The service consumer obtains the address information of the service provider by querying the service registration center, so that it can dynamically initiate calls.

1.2 If there are multiple service providers, how should consumers choose?

In actual applications, there may be multiple service providers that provide the same service. In this case, the service consumer needs to choose an appropriate provider to initiate the call. The selection can be based on factors such as load balancing, performance indicators, and health status.

Solution: Load Balancing

  • Load balancing is a strategy used to distribute requests among multiple service providers to achieve balanced load.
  • Common load balancing strategies include polling, random, weighted polling, weighted random, etc. Different strategies are suitable for different scenarios.

1.3 How do consumers know the health status of service providers?

In a microservice architecture, the health status of service providers is very important information to service consumers. If a service provider fails or is unavailable, service consumers need to avoid making requests to it to ensure system stability and reliability.

Solution: Health Check and Fault Tolerance Mechanism

  • Health check is a mechanism for monitoring the health status of service providers, usually performed by a service registry.
  • Service consumers can determine whether the service provider is available based on the results of the health check, and thus decide whether to initiate a call.
  • The fault tolerance mechanism can help service consumers handle failures that may occur during remote calls, such as timeouts, retries, degradations, etc.

Among them, Eureka is a solution for service registration and discovery. It solves some key problems in microservice invocation through the service registration center.

2. What is Eureka

Eureka is an open source service registration and discovery framework provided by Netflix, which is used to build distributed systems based on microservice architecture. It solves the problems of dynamic registration, discovery and load balancing of services in the microservice architecture, and is one of the important tools for building scalable and high-availability microservices.

2.1 Core concepts of Eureka

  • Service registration

In the microservice architecture, the service provider registers its own information to the Eureka registration center at startup, including service name, network address, etc. In this way, the Eureka registration center knows which services are available in the system.

  • service discovery

Service consumers can obtain information about available services by querying the Eureka registry to decide which services to call. The Eureka registry maintains a list of service instances, including the network address of each service.

  • Heartbeat and health check

The Eureka registry periodically sends heartbeat requests to the service provider to detect whether the service is still available. If a service does not send a heartbeat within a certain period of time, Eureka marks it as unavailable. This enables monitoring of service health status.

  • load balancing

The Eureka client integrates the Ribbon load balancer, which can achieve load balancing among multiple service providers. By using Ribbon, the service consumer can select an appropriate service provider to initiate the call.

Advantages of Eureka

  1. Simplified service invocation: Eureka provides a simple API, making service registration, discovery and invocation very easy.

  2. High availability: Eureka supports cluster deployment of service registration centers and ensures high availability of registration centers through mutual registration.

  3. Load balancing: Integrated Ribbon load balancer can realize request distribution to multiple service providers and improve system performance and stability.

  4. Dynamic expansion: Eureka supports dynamic registration and deregistration of services to adapt to dynamic changes in service instances.

  5. Health check: Through heartbeat and health check, Eureka can detect unavailable service instances in time to ensure high availability of services.

Overall, Eureka is a powerful service registration and discovery framework that provides reliable infrastructure support for building microservice architecture.

2.2 Eureka’s solution to the microservice calling problem

  1. How do service consumers obtain the address information of service providers?

    • Eureka registration center: The service provider registers its address information to the Eureka registration center when starting. Service consumers can obtain the address information of service providers by querying the Eureka registration center.
  2. If there are multiple service providers, how should consumers choose?

    • Load balancing: Eureka supports load balancing, and service consumers can use load balancing strategies to select an appropriate service provider. The Eureka client integrates the Ribbon load balancer, which can easily achieve load balancing.
  3. How do consumers know the health status of service providers?

    • Health check: The Eureka registration center regularly performs health checks on service providers. If a service provider fails, Eureka will mark it as unavailable. Service consumers can filter out unavailable service providers when querying the service list to ensure that only healthy services are selected.

To sum up, Eureka provides a mechanism for service registration and discovery, and integrates functions such as load balancing and health checking, effectively solving key issues in microservice invocation. By using Eureka, service calls in microservice architecture become more flexible, reliable and highly available.

3. The principle of Eureka

Eureka is a service registration and discovery framework provided by Netflix. Through the eureka-serverand eureka-clienttwo parts working together, it realizes the functions of dynamic registration, discovery, load balancing and health check of services in the microservice architecture. Below we will take a closer look at how Eureka works.

3.1 Core components of Eureka

3.1.1 eureka-server

  • Service registration center: eureka-server Acts as a service registration center, responsible for receiving service provider registration information and maintaining the registry.

  • Service registry: The service provider eureka-serverregisters its own information, including service name, network address, etc., with the service provider at startup to form a service registry.

  • Health check: eureka-server Send heartbeats to the service provider regularly and maintain the health status of the service through health checks.

3.1.2 eureka-client

  • Service provider: Each service module in the microservice registers its own service eureka-clientwith .eureka-server

  • Service consumer: The service consumer in microservices achieves service discovery by obtaining information about available services eureka-clientfrom .eureka-server

  • Load balancing: eureka-client Integrated Ribbon load balancer can achieve load balancing among multiple service providers and improve system performance and reliability.

3.2 Eureka workflow

Eureka's workflow can be represented by the following figure:

Eureka workflow

  1. Service registration stage:

    • When a service provider starts, it registers its service information eureka-clientwith .eureka-server

    • Registration includes service name, network address, etc., and the service provider becomes part of the service registry.

  2. Service discovery phase:

    • Service consumers send service discovery requests to eureka-clientvia eureka-server.

    • eureka-serverReturns information about available services, including service names and corresponding network addresses.

    • The service consumer selects a service provider based on the load balancing policy.

  3. Health inspection and maintenance:

    • eureka-serverPeriodically sends heartbeats to the service provider to check the health of the service.

    • If a service provider does not send heartbeats for a long time, eureka-servermark it as unavailable.

    • Unavailable services will be removed from the service registry to maintain the accuracy of the service registry.

Through the above process, Eureka realizes dynamic registration and discovery of services, ensuring the high availability and elastic expansion capabilities of the microservice architecture. Eureka's principle design makes calls between microservices more flexible and reliable.

4. Build Eureka service

The steps to build the Eureka service in the Spring Cloud Demo code are as follows:

  1. Create a project and introduce spring-cloud-starter-netflix-eureka-serverdependencies
<!-- eureka 服务端-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
  1. Write startup class and add @EnableEurekaServerannotations
@EnableEurekaServer // 开启 EurekaServer 自动装配
@SpringBootApplication
public class EurekaApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(EurekaApplication.class, args);
    }
}
  1. Add application.ymlfiles and write the following configuration
server:
  port: 10086
spring:
  application:
    name: eurekaservice # 服务的名称
eureka:
  client:
    service-url: # eureka 的地址信息
      defaultZone: http://127.0.0.1:10086/eureka/ # eureka 也是一个微服务,因此启动的时候也会将自己注册进 eureka 中(为集群起作用)

After completing all the above steps, you can run EurekaApplication the startup class, and then you can access the address: http://localhost:10086/.

If the page that appears at this time is as follows, it means that the Eureka service has been set up successfully: what is shown

below Instances currently registered with Eurekais the service currently registered in Eureka.

5. Registration service

5.1 Registration user-serviceService

The steps to user-serviceregister the service into EurekaServer are as follows:

  1. Introduce dependencies into user-servicethe projectpom.xmlspring-cloud-starter-netflix-eureka-client
 <!-- eureka 客户端-->
 <dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
 </dependency>
  1. In application.ymlthe file, write the following configuration
spring:
  application:
    name: userservice
eureka:
  client:
    service-url: 
      defaultZone: http://127.0.0.1:10086/eureka/ 

At this point we found that this configuration is basically the same as the configuration when building EurekaServer above. The reason is that Eureka will also register itself into EurekaServer when it starts, and the function of this configuration is to register the specified service (distinguished by ) to application namethe defaultZonecorresponding Address in EurekaServer.

5.2 Registration order-serviceService

  1. Introduce dependencies into order-servicethe projectpom.xmlspring-cloud-starter-netflix-eureka-client
 <!-- eureka 客户端-->
 <dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
 </dependency>
  1. In application.ymlthe file, write the following configuration
spring:
  application:
    name: orderservice
eureka:
  client:
    service-url: 
      defaultZone: http://127.0.0.1:10086/eureka/ 

At this point, start the user-serviceand order-serviceservices, and when you visit again, http://localhost:10086/you will find that the service has been successfully registered in EurekaServer:

5.3 Start multiple instances of the same service

In addition, in IDEA, we can start multiple instances of a service at the same time. We only need to ensure that the port numbers of different instances do not conflict.

For example, I want to add two user-serviceservice instances at this time. The steps are as follows:

  1. Right-click UserApplicationand select Copy ConfigurationCopy

  2. Then make the following settings

    -Dserver.port=8082to reset the port number to 8082 for this configuration. You can copy another configuration in the same way.

Start both instances and visit again http://localhost:10086/:


At this time, you can find that user-servicethe services of the two new instances have also been successfully registered in EurekaServer.

6. Discovery of services

After registering the service to EurekaServer, all you need to do is to pull the service. The pull of the service in EurekaServer is based on 服务名称obtaining a list of services, and then selecting 负载均衡a service from the service list.

At this time, if we want order-serviceto be able to pull user-servicethe services registered in EurekaServer, we need to perform the following operations:

  1. Modify order-servicethe code, modify the accessed url path, and replace the IP and port with the service name
public Order queryOrderById(Long orderId) {
    
    
    // 1. 查询订单
    Order order = orderMapper.findById(orderId);

    // 2. 查询用户
    // 2.1 构建查询用户的 url
    String url = "http://userservice/user/" + order.getUserId();

    // 2.2 使用 RestTemplate 远程调用查询用户
    User user = restTemplate.getForObject(url, User.class);

    // 3. 封装 user 信息
    order.setUser(user);

    // 4.返回
    return order;
}

userserviceHere, the service name is used instead of user-servicethe service IP and port number.

  1. Add load balancing annotations in order-servicethe service startup OrderApplicationclassRestTemplate@LoadBalanced
@SpringBootApplication
public class OrderApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(OrderApplication.class, args);
    }

    /**
     * 创建 RestTemplate 并注册到 Spring 容器
     */
    @LoadBalanced // 负载均衡
    @Bean
    public RestTemplate restTemplate(){
    
    
        return new RestTemplate();
    }
}

At this point, restart the service and you can successfully access the services provided order-serviceby EurekaServer .user-service

At this time, clear user-servicethe log records of the three service instances, and then query the order information three times in a row in the browser:



It can be seen from this that the three instances each bear one service request, indicating that the strategy adopted by the load balancing at this time is a polling method.

Guess you like

Origin blog.csdn.net/qq_61635026/article/details/133356097