Spring Cloud Framework Learning - Registration Center Spring Cloud Eureka

1. Introduction to Eureka

Eureka is a service registry provided by Netflix. Eureka implements service registration and discovery based on REST. Eureka is encapsulated in Spring Cloud. On the basis of Eureka, some configurations are optimized and a visual interface is provided, which can easily view the registration status of services and the running status of the service registry cluster.

Euraka consists of two parts: server and client. The server is the registry, which is used to receive registrations from other services; the client is divided into service providers and service consumers, and is a Java client. As shown below:
insert image description here

2. Eureka build

Eureka itself is developed in Java, and Spring Cloud uses Spring Boot technology to encapsulate Eureka. It is very convenient to use Eureka in Spring Cloud. You only need to introduce dependencies: spring-cloud-starter-netflix-eureka-server, and you can start it like a normal Spring Boot project.

1. Create a Spring Boot project and add Eureka dependencies.
insert image description here
2. After the project is created, add the annotation @EnableEurekaServer to the startup class to identify the project as Eureka Server.

@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
    
    

  public static void main(String[] args) {
    
    
    SpringApplication.run(EurekaApplication.class, args);
  }
}

3. Add basic configuration information in application.properties:

#当前服务的名字
spring.application.name=eureka
#端口号(Eureka后台管理端端口)
server.port=1111
#默认情况下,Eureka Server也是一个普通的微服务,所以当它还是注册中心时,就有两层身份:
#1.注册中心;2.普通服务。默认当前eureka server自动把自己注册到注册中心中,
# 通过eureka.client.register-with-eureka=false设置不注册
eureka.client.register-with-eureka=false
#表示是否从Eureka Server上获取注册信息
eureka.client.fetch-registry=false

4. After the configuration is complete, you can start the project and visit http://localhost:1111 in the browser to view the Eureka background management page.
insert image description here

3. Eureka cluster

In the Spring Cloud architecture, if there is only one registry, if a failure occurs, the entire service environment will be unavailable, so we need to build an Eureka registry cluster to achieve load balancing and fault tolerance. Schematic diagram of the Eureka cluster architecture diagram: The
insert image description here
principle of Eureka cluster construction is to register with each other. In this cluster architecture, data synchronization is performed between Eureka Servers, and all nodes are equal without distinguishing between master and slave nodes. The nodes register with each other through the top serviceUrl to form a cluster, thereby improving the availability of the nodes.

In a Eureka server cluster, if a single node fails, the Eureka client will automatically switch to the new Eureka server. Each Eureka server node synchronizes data with each other. The connection method of the Eureka server can be a single line, the connection method is a->b->c, and the data of node a will also be synchronized with c. But this is not recommended. When we configure serviceUrl, you can specify multiple registration addresses, i.e. a can register on b or c at the same time.

4. Eureka Architecture

Eureka consists of two components: Eureka Server and Eureka Client.
insert image description here

4.1 Eureka Server

Eureka Server mainly has three functions:

  1. Service registration, all services are registered on Eureka Server. After each microservice node is started, it will be registered in Eureka Server, so that the service registry in Eureka Server will store the information of all available service nodes, and the information of service nodes can be seen intuitively in the interface.
  2. Provides a registry, which is a list of services registered on Eureka Server. Eureka Client needs to obtain this registry when calling the service. Generally speaking, this registry will be cached. If the cache fails, it will directly obtain the latest registry.
  3. Synchronization status, Eureka Client synchronizes the current registry status with Eureka Server through registration, heartbeat and other mechanisms.

4.2 Eureka Client

Eureka Client is mainly used to simplify the interaction between each service and Eureka Server. Eureka Client will automatically pull updates and cache the information in Eureka Server, so that even if all nodes of Eureka Server are down, Eureka Client can still obtain the service it wants to call. (but the address may be inaccurate).

Eureka Client provides the following functions:

  • service registration

The service provider registers itself with the service registry Eureka Server,The so-called service provider is just a business division, which is essentially an Eureka Client. After Eureka Client registers with Eureka Server, it will provide its own metadata information, such as IP address, port, name, running status, etc.

  • Service renewal

After Eureka Client registers with Eureka Server, == By default, Eureka sends a heartbeat message to Eureka Server every 30s to tell Eureka Server that it is still running. ==If the Eureka Server does not receive a renewal message from the Eureka Client for 90 seconds, the Eureka Server will consider the Eureka Client to be offline and remove it from the service registration list.

Service renewal related functions have two related properties (generally not recommended to modify):

#服务续约时间,默认30s
eureka.instance.lease-renewal-interval-in-seconds=30
#未续约的服务失效时间,默认90s
eureka.instance.lease-expiration-duration-in-seconds=90
  • service offline

When Eureka Client goes offline, it will actively send a message to tell Eureka Server that it is going offline.

  • Get registry information

Eureka Client obtains service registration information from Eureka Server and caches it locally. When the local client needs to call the remote service, it will look up the IP address, port and other information corresponding to the remote service from the information. The service registration information cached on the Eureka Client will be updated periodically (30 seconds). If the registry information returned by the Eureka Server is different from the locally cached registry information, the Eureka Client will automatically process it.
There are two properties involved:

#是否获取注册表信息,默认为true
eureka.client.fetch-registry=true
#定期更新的时间间隔,默认为30秒
eureka.client.registry-fetch-interval-seconds=30

4.3 Eureka self-protection

By default, if Eureka Server does not receive the heartbeat of a microservice instance within a certain period of time (default 90 seconds), Eureka Server will log out the microservice instance. However, when a network partition failure occurs, delays, freezes, and congestion, the microservice and Eureka Server cannot communicate normally. However, because the microservice is actually healthy, the microservice instance should not be offline at this time. Eureka solves this problem through "self-protection mode" - when the Eureka Server node loses too many clients in a short period of time, then Eureka enters the self-protection mode, and the Eureka Server will not immediately offline the Eureka Client service.

5. Service Registration

Service registration is to register a microservice with Eureka Server, so that when other services want to call the service, they only need to query the information of the service from Eureka Server, and then complete the service call.

To create a service provider, just add the following two dependencies to your Spring Boot project:

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

Then configure the registration address of the project in application.properties, you can register the service provider Provider to the Eureka Server:

#服务名
spring.application.name=provider
#服务端口号
server.port=1113
#注册中心url地址
eureka.client.service-url.defaultZone=http://localhost:1111/eureka

Then, start the service registry Eureka Server first, and then start the service provider after its startup is complete. After the two are successfully started, enter in the browser to http://localhost:1111view the registration information in the current service registration center.
insert image description here

6. Service consumption

First provide an interface in the module provider:

@RestController
public class HelloController {
    
    
  @Value("${server.port}")
  Integer port;

  @GetMapping("/hello")
  public String hello(){
    
    
    return "hello world port:"+port;
  }
}

Then create a consumer module and also add spring-boot-starter-web and spring-cloud-starter-netflix-eureka-client dependencies.

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

After the creation is complete, configure the registration information in application.properties

#服务名称
spring.application.name=consumer
#端口号
server.port=1114
#注册中心的url地址
eureka.client.service-url.defaultZone=http://localhost:1111/eureka

Then provide an interface, consume the interface provided by the service provider, and then use the DiscoveryClient tool provided by Eureka Client to query the detailed information of a service from Eureka Server according to the service name, and use the RestTemplate tool class to initiate the request.

@SpringBootApplication
public class ConsumerApplication {
    
    

  public static void main(String[] args) {
    
    
    SpringApplication.run(ConsumerApplication.class, args);
  }

  @Bean
  RestTemplate restTemplate(){
    
    
    return new RestTemplate();
  }
}
@RestController
public class HelloController {
    
    
  @Autowired
  DiscoveryClient discoveryClient;
  @Autowired
  RestTemplate restTemplate;

  @GetMapping("/hello2")
  public String hello2(){
    
    
    HttpURLConnection httpConnection=null;
    //如果是集群部署会有多个
    List<ServiceInstance> providerList = discoveryClient.getInstances("provider");
    ServiceInstance provider=providerList.get(0);
    String host = provider.getHost();
    int port=provider.getPort();
    StringBuffer providerUrl = new StringBuffer("http://").append(host)
                                                          .append(":")
                                                          .append(port)
                                                          .append("/hello");
    //通过RestTemplate实现服务的调用
    String result = restTemplate.getForObject(providerUrl.toString(), String.class);
    return result;
  }
}

To configure the load balancing function of RestTemplate, you need to add the annotation @LoadBalanced to enable it

@SpringBootApplication
public class ConsumerApplication {
    
    

  public static void main(String[] args) {
    
    
    SpringApplication.run(ConsumerApplication.class, args);
  }

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

Guess you like

Origin blog.csdn.net/huangjhai/article/details/107501646