Spring Cloud Study Notes [Service Registration and Discovery - Eureka]

What is Service Governance

Service governance is a method of managing and controlling individual services in a distributed system. In a distributed system, each service may be developed, maintained and deployed by different teams or companies, so a mechanism is needed to ensure interoperability and stability between services.
Service governance includes the following aspects:

  • Service registration and discovery: Service providers can register their services to the service registry, and service consumers can find the required services from the registry.
  • Load balancing: Service governance can allocate requests to different service instances according to the load conditions of different services, so as to avoid overloading or under-loading of certain service instances.
  • Fuse and degradation: When a service fails or responds slowly, service governance can prevent the failure or delayed service from affecting the entire system by fusing or degrading.
  • API management: Service governance can manage and restrict service APIs, prevent service providers from abusing APIs, and protect service consumers' data security.
  • Monitoring and alarming: Service governance can monitor and alarm the running status of services, discover and deal with potential problems in time, and ensure the stability and reliability of the system.

Service governance is an important distributed system management method, which can effectively improve system reliability and maintainability, and reduce system operation and maintenance costs.

What is service registration and discovery

Service registration and discovery is a very important part of the microservice architecture, which solves the communication problem between services. In a distributed system, the service provider needs to register its own service information in the service registry, and the service consumer can obtain the service information that needs to be called from the service registry, so as to realize the communication between services. The service registration center can be regarded as the "yellow pages" of the service, including the name, address, port number and other information of the service provider. The service consumer can obtain the information of the service provider by querying the service registration center.

From Eureka's point of view, service registration is to register the service provider's information into the Eureka registry. The service provider needs to send a registration request to the Eureka registration center at startup, and register its own service information (such as service name, IP address, port number, etc.) into Eureka. The service registry will save these service information for use by other service consumers. Service discovery means that service consumers obtain the service information that needs to be called from the Eureka registry. Service consumers can query the service provider's information through the REST API of the Eureka registry to implement calls between services.

Eureka's service registration and discovery mechanism can realize dynamic expansion and contraction of services. When the number of instances of service providers changes, Eureka can automatically update the service information of the registration center, and service consumers can obtain the latest service information, thus ensuring Availability of Services. Eureka also provides a self-protection mechanism. When a service provider fails or the network fluctuates, Eureka can automatically recover and remove unavailable services, thereby improving service reliability and robustness.
insert image description here

Eureka two components

Eureka consists of two main components:

  • Eureka Server: The Eureka server is the service registration center. All service instances need to register their own information with the Eureka server, and send heartbeats to the Eureka server regularly to maintain the validity of the registration information. The Eureka server maintains the registration information of all service instances and provides a REST API interface for clients to query service information.

  • Eureka Client: The Eureka client is a service provider and a service consumer. The service provider registers its own service information with the Eureka server at startup, and sends heartbeats regularly to maintain the validity of the registration information. The service consumer queries the information of the service provider through the Eureka client, and selects one of the service providers to call through the load balancing algorithm.

Multiple clusters can be established between Eureka Server and Eureka Client to achieve high availability and fault tolerance. Eureka servers will register with each other to form an interconnected cluster. When the Eureka client queries the service, it will first query the local Eureka server. If the local Eureka server does not have a corresponding service instance, it will query the registration information on other Eureka servers. Eureka also provides some advanced features, such as security authentication, self-protection mechanism, multi-data center support, etc., to meet the needs of different scenarios.

Eureka build

Build a stand-alone Eureka Server

New module cloud-eureka-server7001
insert image description here
pom.xml

<dependencies>
        <!--eureka-server-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <!--boot web actuator-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--图形监控,以后的swagger和Hystrix要用的-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--一般通用配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
    </dependencies>

application.yml

server:
  port: 7001

eureka:
  instance:
    hostname: localhost #eureka服务端的实例名称
  client:
    #false表示不向注册中心注册自己。
    register-with-eureka: false
    #false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    fetch-registry: false
    service-url:
      #设置与Eureka Server交互的地址查询服务和注册服务都需要依赖这个地址。
      defaultZone: http://${
    
    eureka.instance.hostname}:${
    
    server.port}/eureka/

Start class Eureka7001Application

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

Start the test
Visit http://localhost:7001/ and the display is as follows, indicating that the eureka server has started successfully
insert image description here
Next, we will register the service

Eureka client registration

Transform our previous two demo services auth and user, and register them in Eureka.

user service

pom.xml adds eureka-client dependency

<!--eureka-client-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

application.yml add eureka configuration

eureka:
  instance:
    # 配置eureka的状态显示
    hostname: localhost
    instance-id: ${
    
    eureka.instance.hostname}:${
    
    spring.application.name}:${
    
    server.port}
  client:
    #表示是否将自己注册进EurekaServer默认为true。
    register-with-eureka: true
    #是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetchRegistry: true
    service-url:
      defaultZone: http://localhost:7001/eureka

Add annotations to the startup class

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

user service

The configuration is the same as auth one, so I won’t write it in detail

single point test

First start the Eureka7001Application server;
then start two Eureka clients.
insert image description here
Service registered successfully

Build a cluster Eureka Server

Build a cluster of Eureka registration centers to achieve load balancing + fault tolerance.
Refer to cloud-eureka-server7001 and create a new cloud-eureka-server7002

Modify the host file C:\Windows\System32\drivers\etc, add a mapping, and distinguish the instance names so that you can see the effect easily

  • 127.0.0.1 eureka7001.com
  • 127.0.0.1 eureka7002.com

Modify application.yml
host name modification: change to the above fake domain name
defaultZone modification: write in all other eureka nodes except yourself, now write one, and then add commas to separate multiple eureka nodes.
7001 service:
insert image description here
7002 service:
insert image description here

Cluster startup test

insert image description here

Sub-service cluster construction

Transform the user service into a cluster, test auth through the service name, and call multiple services of the user.

  • Referring to the user service,
    insert image description here
    the ports of the module application.yml of a new user2 are different, and the others are the same
    insert image description here
  • Then change the addresses of all sub-services to cluster addresses, separated by commas
    insert image description here
  • Start all the services, pay attention to the order to start the eureka server first
    insert image description here
    and see that all three services are registered successfully

Service invocation and load balancing

In the last issue, auth calling the user service was actually hard-coded.
insert image description here

  • Now we change to call by the microservice name registered on eureka
    insert image description here
  • Since the service is a cluster, there are multiple services under LF-USER (services on port 9001 and port 9011), you need to use the @LoadBalanced annotation to give RestTemplate the ability to load balance, and the default should be to poll services on ports 9001 and 9011. At the same time, add the port number to the returned information to facilitate testing.
@Configuration
public class ApplicationContextConfig {
    
    

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

}

Test effect

The first request:
insert image description here
the second request:
insert image description here
so far the load balancing effect is achieved, and the 9001/9002 ports appear alternately

Guess you like

Origin blog.csdn.net/qq_33129875/article/details/129539437