服务治理:Spring Cloud Eureka

spring cloud与dubbo关系

    

Eureka与zk

从cap原则来分析:zk中有主从区别,而eureka是集群。zk注重cp,eureka注重ap。


功能

服务注册中心、服务注册、服务发现、服务提供者、服务消费者、eureka服务端、eureka客户端


注册中心高可用

    假设注册中心部署两台服务器A(192.168.33.11)和B(192.168.33.12),将A注册中心url指向B,B指向A。

A:

server:
  port: 10001
eureka:
  instance:
    hostname: localhost
  client:
    serviceUrl:
      defaultZone: http://192.168.33.12:10002/eureka/

B:

server:
  port: 10002
eureka:
  instance:
    hostname: localhost
  client:
    serviceUrl:
      defaultZone: http://192.168.33.11:10001/eureka/

    

服务发现

    开启服务发现:    启动类注释

@EnableDiscoveryClient


服务注册

    服务提供者启动的时候,会想注册中心发送自身信息来注册自己,为双层key的map,第一层key为服务名,第二层key为实例名。

注册中心集群信息同步:

    服务注册只会注册到单台注册中心,然后集群之间同步数据

服务续约

    服务提供者主动心跳到注册中心,告知自己还活着,涉及两个属性

eureka:
  instance:
    lease-expiration-duration-in-seconds: 30 #服务失效时间,默认90秒
    lease-renewal-interval-in-seconds: 10  #心跳频率,默认30秒

获取服务

    注册中心维护一份服务清单,消费者拉取维护在本地,涉及属性

eureka:
  client:
    fetch-registry: true #开启拉取功能
    registry-fetch-interval-seconds: 30 #服务清单刷新频率

服务调用

    消费者通过ribbon实现客户端负载调用具体服务实例。服务注册到注册中心涉及两个概念:Region和Zone,关系是1对多,ribbon会优先访问同一Zone的服务

服务下线

服务提供者发送请求给注册中心,注册中心将服务状态为down,并且传播

失效剔除

有时候服务非正常down掉,没有主动通知注册中心服务失效,这时就需要注册中心自己完成这个任务。注册中心主动剔除不在活服务,启动定时任务,每隔60秒执行一次,清除90秒还未续约的服务

自我保护

首先对Eureka注册中心需要了解的是Eureka各个节点都是平等的,没有ZK中角色的概念, 即使N-1个节点挂掉也不会影响其他节点的正常运行。

默认情况下,如果Eureka Server在一定时间内(默认90秒)没有接收到某个微服务实例的心跳,Eureka Server将会移除该实例。但是当网络分区故障发生时,微服务与Eureka Server之间无法正常通信,而微服务本身是正常运行的,此时不应该移除这个微服务,所以引入了自我保护机制。自我保护模式正是一种针对网络异常波动的安全保护措施,使用自我保护模式能使Eureka集群更加的健壮、稳定的运行。

自我保护机制的工作机制是如果在15分钟内超过85%的客户端节点都没有正常的心跳,那么Eureka就认为客户端与注册中心出现了网络故障,Eureka Server自动进入自我保护机制,此时会出现以下几种情况:
1、Eureka Server不再从注册列表中移除因为长时间没收到心跳而应该过期的服务。
2、Eureka Server仍然能够接受新服务的注册和查询请求,但是不会被同步到其它节点上,保证当前节点依然可用。
3、当网络稳定时,当前Eureka Server新的注册信息会被同步到其它节点中。

因此Eureka Server可以很好的应对因网络故障导致部分节点失联的情况,而不会像ZK那样如果有一半不可用的情况会导致整个集群不可用而变成瘫痪。

此功能具体是打开还是关闭要跟具体情况而定了。


源码

1. 是纯正的 servlet 应用,需构建成war包部署 
2. 使用了 Jersey 框架实现自身的 RESTful HTTP接口 
3. peer之间的同步与服务的注册全部通过 HTTP 协议实现 
4. 定时任务(发送心跳、定时清理过期服务、节点同步等)通过 JDK 自带的  Timer  实现 
5. 内存缓存使用Google的guava包实现

服务端

入口:

/***
 * 注解该类会被spring初始化
 * 初始化服务端的属性类并且传播集群
 */
@Configuration
public class EurekaServerInitializerConfiguration
        implements ServletContextAware,
        SmartLifecycle,
        Ordered {

    public void start() {
        new Thread(new Runnable(){

            @Override
            public void run() {
                try {
                    EurekaServerInitializerConfiguration.this.eurekaServerBootstrap.contextInitialized(EurekaServerInitializerConfiguration.this.servletContext);
                    log.info((Object)"Started Eureka Server");
                    EurekaServerInitializerConfiguration.this.publish(new EurekaRegistryAvailableEvent(EurekaServerInitializerConfiguration.this.getEurekaServerConfig()));
                    EurekaServerInitializerConfiguration.this.running = true;
                    EurekaServerInitializerConfiguration.this.publish(new EurekaServerStartedEvent(EurekaServerInitializerConfiguration.this.getEurekaServerConfig()));
                }
                catch (Exception ex) {
                    log.error((Object)"Could not initialize Eureka servlet context", (Throwable)ex);
                }
            }
        }).start();
    }
}

服务注册中心-服务注册:

    /***
     * package org.springframework.cloud.netflix.eureka.server.InstanceRegistry;
     * 注册中心注册
     * @param info
     * @param isReplication
     */
    public void register(InstanceInfo info, boolean isReplication) {
        this.handleRegistration(info, this.resolveInstanceLeaseDuration(info), isReplication);//将注册信息传播出去
        super.register(info, isReplication);//调用父类注册方法注册
    }

    客户端

        核心类为netflix包下的DiscoveryClient类,客户端主要功能:向注册中心注册服务实力、租约、取消租约、获取注册中心实力列表、维护注册中心url列表

维护注册中心url列表:

package com.netflix.discovery.endpoint;
public class EndpointUtils {
/***
     * 获取注册中心url map
     * @param clientConfig     加载配置文件内容
     * @param instanceZone
     * @param preferSameZone
     * @return    map  key:zone   value:url list
     */
    public static Map<String, List<String>> getServiceUrlsMapFromConfig
            (EurekaClientConfig clientConfig, String instanceZone, boolean preferSameZone) {
        //定义返回map,key为zone
        Map<String, List<String>> orderedUrls = new LinkedHashMap();
        String region = getRegion(clientConfig);
        String[] availZones = clientConfig.getAvailabilityZones(clientConfig.getRegion());
        if(availZones == null || availZones.length == 0) {
            availZones = new String[]{"default"};
        }

        int myZoneOffset = getZoneOffset(instanceZone, preferSameZone, availZones);
        String zone = availZones[myZoneOffset];
        //zone可以多个,逗号拆分存list
        List<String> serviceUrls = clientConfig.getEurekaServerServiceUrls(zone);
        if(serviceUrls != null) {
            orderedUrls.put(zone, serviceUrls);
        }

        int currentOffset = myZoneOffset == availZones.length - 1?0:myZoneOffset + 1;

        while(currentOffset != myZoneOffset) {
            zone = availZones[currentOffset];
            serviceUrls = clientConfig.getEurekaServerServiceUrls(zone);
            if(serviceUrls != null) {
                orderedUrls.put(zone, serviceUrls);
            }

            if(currentOffset == availZones.length - 1) {
                currentOffset = 0;
            } else {
                ++currentOffset;
            }
        }

        if(orderedUrls.size() < 1) {
            throw new IllegalArgumentException("DiscoveryClient: invalid serviceUrl specified!");
        } else {
            return orderedUrls;
        }
    }
}
/***
     * package com.netflix.discovery.DiscoveryClient;
     * 服务注册、续约和获取
     */
    private void initScheduledTasks() {
        int renewalIntervalInSecs;//心跳频率
        int expBackOffBound;//定时任务延迟执行
        if(this.clientConfig.shouldFetchRegistry()) {//服务获取,
            renewalIntervalInSecs = this.clientConfig.getRegistryFetchIntervalSeconds();
            expBackOffBound = this.clientConfig.getCacheRefreshExecutorExponentialBackOffBound();
            this.scheduler.schedule
                    (new TimedSupervisorTask("cacheRefresh", this.scheduler,
                            this.cacheRefreshExecutor, renewalIntervalInSecs,
                            TimeUnit.SECONDS, expBackOffBound,
                            new DiscoveryClient.CacheRefreshThread()),
                            (long)renewalIntervalInSecs, TimeUnit.SECONDS);
        }

        if(this.clientConfig.shouldRegisterWithEureka()) {//服务注册\续约
            renewalIntervalInSecs = this.instanceInfo.getLeaseInfo().getRenewalIntervalInSecs();
            expBackOffBound = this.clientConfig.getHeartbeatExecutorExponentialBackOffBound();
            logger.info("Starting heartbeat executor: renew interval is: " + renewalIntervalInSecs);
            //续约
            this.scheduler.schedule(new TimedSupervisorTask("heartbeat", this.scheduler, this.heartbeatExecutor, renewalIntervalInSecs, TimeUnit.SECONDS, expBackOffBound, new DiscoveryClient.HeartbeatThread(null)), (long)renewalIntervalInSecs, TimeUnit.SECONDS);
            this.instanceInfoReplicator = new InstanceInfoReplicator(this, this.instanceInfo, this.clientConfig.getInstanceInfoReplicationIntervalSeconds(), 2);
            this.statusChangeListener = new ApplicationInfoManager.StatusChangeListener() {
                public String getId() {
                    return "statusChangeListener";
                }

                public void notify(StatusChangeEvent statusChangeEvent) {
                    if(InstanceInfo.InstanceStatus.DOWN != statusChangeEvent.getStatus() && InstanceInfo.InstanceStatus.DOWN != statusChangeEvent.getPreviousStatus()) {
                        DiscoveryClient.logger.info("Saw local status change event {}", statusChangeEvent);
                    } else {
                        DiscoveryClient.logger.warn("Saw local status change event {}", statusChangeEvent);
                    }

                    DiscoveryClient.this.instanceInfoReplicator.onDemandUpdate();
                }
            };
            if(this.clientConfig.shouldOnDemandUpdateStatusChange()) {//当服务down的时候,通知注册中心更新
                this.applicationInfoManager.registerStatusChangeListener(this.statusChangeListener);
            }
            //服务注册
            this.instanceInfoReplicator.start(this.clientConfig.getInitialInstanceInfoReplicationIntervalSeconds());
        } else {
            logger.info("Not registering with Eureka server per configuration");
        }

    }


配置信息

服务注册类配置(EurekaClientConfigBean)

registryFetchIntervalSeconds:客户端启动时会从服务端获取注册信息,然后定时增量获取,这个参数为时间间隔

cacheRefreshExecutorExponentialBackOffBound :如果获取失败,也是以2的指数形式延长重试时间,直到达到registryFetchIntervalSeconds * cacheRefreshExecutorExponentialBackOffBound 这个上限,之后一直以这个上限值作为重试间隔,直至重新获取到注册信息,并且重新尝试获取注册信息的次数是不受限制的。 

initialInstanceInfoReplicationIntervalSeconds:客户端启动后,首次发送客户端实例信息到服务端的时间

instanceInfoReplicationIntervalSeconds:客户端更新实例信息到服务端时间间隔

eurekaServiceUrlPollIntervalSeconds:轮询enreka服务端地址更改的间隔时间

eurekaServerReadTimeoutSeconds:读取server信息超时时间

eurekaServerConnectTimeoutSeconds:连接server超时时间

猜你喜欢

转载自blog.csdn.net/u011064905/article/details/80195454