[Spring Cloud] service registration and discovery component --Eureka (b)

A, Eureka principle

1, Chart

First look at the structure of the official map of eureka

  All applications as Eureka Client interaction and Eureka Server, a service provider registration information to start your own IP, port, providing services to Eureka Server, update and regularly renew their status.

  Service consumers through Eureka Server discovery to obtain the desired information service provider address, and then initiate a call to the remote service provider.

  In order to ensure high availability Eureka registry, you can cluster deployment, informing other Server node when a node information and updates, different nodes of Eureka data synchronization via Replicate.

2, the basic principle

In the process of Eureka response, there are three roles, namely Eureka, service providers, service consumers;

  • After the service starts, the service provider registered with the Eureka own information, such as call address, service information, etc.
  • Eureka register for the service center, exposed out its address, responsible for the management, records information service providers, as well as meet the requirements of the service provider returns the address list service consumers
  • Service consumer subscription service to Eureka, express their needs, and then get a message service provider, you can remotely call

Eureka comprises two components: Eureka Server and Eureka Client, role is as follows:

  • Eureka Client is a Java client, and is mainly used to simplify the interaction of Eureka Server
  • Eureka Server provides the ability to service discovery, service starts when the individual micro, register their information to the Eureka Server through Eureka Client, Server stores information about the service
  • After the service starts micro periodically (the default is 30s) to send heartbeat information to the Server, in order to renew their information, time-out (the default is 90s) did not receive a heartbeat, Server will log off the service node
  • After setting Eureka Server logs off from a service provider node, and to publish the service to other subscribers, subscribers to update the local cache information
  • In a cluster, each Eureka Server is also the Eureka Client, registration with each other to complete the service registry message synchronization to avoid nodes because of a Eureka hang and cause the entire micro Services Architecture hang
  • Eureka Client Server will cache the information in before calling service, first check whether there is information about the cache, the local cache is updated regularly

3, self-protection mechanism

   Since the timeout (default 90s) After the heartbeat renewal information service provider has not been accepted, Eureka Server for the cancellation of the instance, but often due to the cross-process service calls between micro, subject to greater impact network traffic situation, such as in micro service is normal, but when the network partition fails, log off the service instance will most micro service is not available, in order to avoid such a situation, the introduction of self-protection mechanism of Eureka. The principle of self-protection mechanism that, when a Eureka Server nodes in a short time lost too many of the client node, the node enters the self-protection mechanism, no longer write off any micro service instance, when a network failure returned to normal, the node automatically exit the self-protection mechanism.

  Self-protection mechanism based on self-protection threshold to distinguish between Eureka Server or a problem resulting in Eureka Client Service failed to renew on time.

4, service mechanism

   Services by a service registration process is sequentially, periodically and renewed service, if the service stop normal, then send a logout request to the registration center before stopping the service, if a normal non-stop, will not be sent, the service by the Eureka Server excluding the initiative.

4.1, service registration mechanism --Register

For registration services, and provider status at the time of the service provider to start the update service status change.

After the server to accept service registration, save your registration information; then update the self-protection threshold, excluding mechanism for use of the service; the last synchronization service information, synchronize this event to other Eureka Server nodes.

4.2, Service Renewal mechanism --Renew

Called by the service provider regularly, send heartbeat information to renew the service server.

After receiving the registry renewal request, the recent renewal time update service object, then synchronization service information, synchronize this event to other Eureka Server nodes.

We will first determine whether the service before removing the service expires, if one of the conditions is that the recent expiration of the current contract period and the time difference is greater than a threshold value.

4.3, the service cancellation mechanism --Cancel

When invoked by the service provider shut down, to cancel your service.

After registration mechanism similar to, cancel requests received in the registry, first delete the message, and then updates (excluding services) threshold, the final event to synchronize other Eureka Server nodes.

4.4, excluding service mechanism --Eviction

  Excluding service consists of three steps, first determine whether the service reject condition is satisfied, then find expired service, excluding the final implementation services.

Determine whether the service reject the conditions are met - mainly to see whether to open self-protection mechanism Eureka

  Case closed self-protection mechanisms directly into the next step;

  The case of open self-protection mechanism, only the actual contract is greater than the number of self-protection threshold (indicating that most services are available to determine Client is a problem, on the contrary judged Server out of the question), will enter service culling process.

  Self-service protection threshold = Total * (60s / client renewal interval) * Self-protection threshold factor.

Find expired service

  Through all services, determine the most recent renewal time from the current value of the time difference is greater than the set threshold, it is marked as expired, and save all expired service set.

Excluding service

  Through all the expired service, by shuffling algorithm ensures that every time you want to eliminate a fair selection of services, and finally removed.

4.5, the pull service --Fetch Registries

Called by the service consumer, find the center of the same name registration service list.

Service providers usually list the address information in a local cache, the default cache information is updated once every 30s.

4.6, service synchronizes --Replicate

Used to implement the service information between Server synchronization service provider can only update information in the server cluster on a server registration.

Node accepts registration requests again forwards the request to the other server nodes, interfaces, and the like identical call parameters, except those marked isReplicate = true, to avoid repeated isochronous Replicate.

Information synchronous to asynchronous mode is complete, all the nodes does not guarantee strong consistency of information can only ensure that the final agreement.

4.7, adding new nodes (New Server Initialize)

The new server node join, start itself as consumers pull all registered information, and then register each service to its own node, mark isReplicate = true, complete initialization.

4.8, the storage structure - two Hash Map

Second, the service registry of choice

1, CAP principles

  CAP theorem: In a distributed system, the consistency (Consistency), availability (Availability), fault tolerance partition (Partition tolerance), three can be simultaneously obtained.

  • Consistency: In a distributed system, all data is backed up at the same time whether the same value
  • Availability: part of a cluster node failure, the normal response of the cluster can also read and write requests to the client
  • Subdivision fault tolerance: hang up after a node failure, does not affect the other nodes, i.e., high availability

  CAP theory explained in a distributed system, while achieving a maximum of two of them, but due to problems delayed loss of current network hardware is bound to occur, so the partition fault tolerance is necessary, so only in the middle of consistency and availability trade off.

2, the choice of registry

  The current mainstream Register Center Eureka, Zookeeper, consul and so on, their different emphases.

2.1, Zookeeper guarantee CP

  Zookeeper after the master node failure because the network lost contact with the other node, the remaining nodes will be re-election leader node, but during the (30 ~ 120s) elections, zk entire cluster is unavailable, although the service can eventually recover but the long lead time of election registration centers are often long-term use is not tolerated.

2.2, Consul guarantee CP

  Consul brings strong consistency is: service registration slower than Eureka, consul of the raft because protocol requires a majority of nodes must have written success was considered a successful registration; When the node hang Leader, during the re-election of the entire non-consul with, at the expense of the availability of the cluster.

2.3, Eureka guarantee AP

  Eureka在设计时优先保证可用性,其中各个节点都是平等的,几个节点挂掉,剩余节点仍能提供注册和查询服务,只要有一台Eureka还在,就能保证服务可用(保证可用性),但不保证查询到的信息时最新的(不保证强一致性);除此之外,由于自我保护机制不再剔除服务实例的节点,仍能接受新服务的注册和查询请求,但不会被同步到其他节点上。

  同时,Eureka还提供客户端(Eureka客户端程序负责向外提供注册与发现服务接口)缓存功能,所以极端情况下,客户端无法访问任何一个Server节点,消费者仍能通过客户端查询与获取注册服务信息。

  因此,Eureka可以很好地应对因网络故障导致部分节点失联的情况,尽可能地保证整个集群的可用性。

三、demo工程的搭建

新建maven工程,删除src文件夹,作为项目运行环境。

1、server节点

新建module名为Server_1,为标准的SpringBoot工程,其目录结构如下。

在pom文件中添加Eureka-server和Eureka-client依赖。

启动类上添加@EnableEurekaServer注解,标注为Eureka Server节点。

在配置文件中增加相关配置信息。

server.port暴露服务端口。

spring.application.name为应用名,应用名为SpringCloud中服务调用的依据。(注:应用名中不可有下划线,否则会调用失败。)

eureka属性有server、client、instance等部分;

  client.register-with-eureka为是否将应用注册到eureka,默认为true,单点server节点指定为false

  client.fetch-registry为是否从注册中心拉取已注册信息,默认为true,单点server节点指定为false

  client.service-url.defaultZone指定注册中心地址

启动应用,访问localhost:1001/即可看到eureka注册中心服务管理界面。

2、服务提供者——Hello_1

新建module名为Hello_1,SpringBoot工程,提供常规的SpringMVC访问控制,目录结构如下。

 添加Eureka-server和Eureka-client依赖。

启动类添加@EnableDiscoveryClient注解,使用@EnableEurekaClient效果一样。

service和controller包中提供MVC的服务实现与访问控制功能。

在配置文件application.yml中,添加相关配置,将该应用注册到之前的Eureka Server节点,注册名为hello-app。

启动应用后,访问localhost:1001/即可看到刚注册的应用。

3、服务消费者——Introduce

 继续新建module名为Introduce,调用hello-app服务。

目录结构仍为SpringBoot工程,实现SpringMVC访问控制。

除了添加Eureka的依赖外,添加Ribbon依赖(客户端负载均衡,后续要用到)。

启动类上加入@EnableEurekaClient注解,并注入RestTemplate Bean,添加@LoadBalanced注解,表明开启负载均衡功能。

controller包内提供访问控制。

 

service包内提供服务的具体实现,此处为对hello-app应用的远程调用,通过构造url,利用RestTemplate发起RestFul请求。

访问的URL构造为http://${请求应用名}/${请求路径}?${可能的参数列表}

不要忘记在配置文件中增加相关配置信息。

 启动应用后,访问localhost:1001/查看应用注册情况,访问localhost:8001/intro?name=world查看服务调用结果。

 

至此,完成了一个单点EurekaServer环境的搭建,并在其上注册两个应用,实现服务间的远程调用。

Guess you like

Origin www.cnblogs.com/iUtopia/p/11493725.html