服务注册与发现之Eureka

服务注册发现-Eureka

    

•基于 REST 的服务,它主要是用于定位服务,以实现 AWS 云端的负载均衡和中间层服务器的故障转移。如果你希望实现一个 AP( Availability and Partition ) 系统, Eureka 是一个很好的选择,并在 Netflix 得到了实战的检验。在出现网络分区时, Eureka 选择可用性,而不是一致性

•默认情况下每个Eureka服务端也是一个Eureka客户端并且通过请求服务的URL去定位一个节点。如果你不提供的话,服务虽然还会运行和工作,但是它不会向你打印一堆关于没有注册的节点日志。

•当一个客户端注册到Eureka,它提供关于自己的元数据(诸如主机和端口,健康指标URL,首页等)之后每 30 秒钟发送心跳以更新自身状态。如果该客户端没能发送心跳更新,它将在 90 秒之后被其注册的 Eureka 服务器剔除。来自任意 zone 的 Application Client 可以查看这些注册信息(每隔 30 秒查看一次)并依此定位自己的依赖应用实例,进而进行远程调用。

Eureka Server 配置

POM

103751_NiI3_3260714.png

Application

@SpringBootApplication
@EnableEurekaServer
public class RegistryApplication extends SpringBootServletInitializer {

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

}

这段很简单启动EurekaServer,就不废话
bootstrap.properties

#系统
spring.application.name=registry
server.port=7070
server.context-path=/
server.uri-encoding=utf-8
management.context-path=/management
info.app.name=${spring.application.name}
info.app.profiles=${spring.profiles.active}
info.app.version=@project.version@
#仅供本地访问
management.address=127.0.0.1
spring.profiles.active=@env@

 

application.properties

#eureka 服务端
#本机是否注册服务
eureka.client.registerWithEureka=false
#启动时是否检测注册客户端
eureka.client.fetchRegistry=false
#启用Ip注册
eureka.instance.perferIpAddress=true
#剔除无效实例频率默认60S
eureka.server.evictionIntervalTimerInMs=10000
#注册服务地址
eureka.client.serviceUrl.defaultZone=http://localhost:7070/eureka/
eureka.instance.metadataMap.management.context-path=${management.context-path}

 

Eureka Client  

@EnableEurekaClient启动客户端

<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
eureka.client.serviceUrl.defaultZone=http://localhost:7070/eureka/
#启用Ip注册
eureka.instance.preferIpAddress=true
#续约心跳时间 默认三十秒
eureka.instance.leaseRenewalIntervalInSeconds=10
#续约时效时间
eureka.instance.leaseExpirationDurationInSeconds=90
#状态页面
eureka.instance.statusPageUrlPath=${management.context-path}/info
#健康检查页面
eureka.instance.healthCheckUrlPath=${management.context-path}/health
#turbine配置
eureka.instance.metadataMap.cluster=MAIN
eureka.instance.metadataMap.management.context-path=${management.context-path}

默认使用hostname注册

可根据eureka.instance.preferIpAddress=true更改为IP

未设置ipaddr或hostname,默认会从hostInfo获取ipAddr 或 hostname

instanceId 默认值为hostname/ipAddr-application.name-port 可自定义修改

instanceId ,hostname,ipaddr 不建议设置,可采用默认

leaseRenewalIntervalInSeconds 默认是30秒,也就是每30秒会向Eureka Server发起Renew(续约)操作

 基本流程

        客户端

                在com.netflix.discovery.DiscoveryClient启动的时候,将本地配置信息注册到注册中心,初始化定时任务,定时调用renew,定时刷新本地缓存(注册中心其他服务信息默认三十秒)

  服务端 

            Eviction(失效服务剔除)用来定期(默认为每60秒)在Eureka Server检测失效的服务,检测标准就是超过一定时间没有Renew的服务。
    默认失效时间为90秒,也就是如果有服务超过90秒没有向Eureka Server发起Renew请求的话,就会被当做失效服务剔除掉。

   服务端有自我保护机制,会在心跳总量无法维持到某一个阈值时触发,触发的结果就是evict过期instance的任务不再驱逐任何实例。这个阈值的单位是分钟,计算方式是当前所有保存的instance,按照每分钟应该提交2次心跳(30秒心跳),再乘以可以配置的最低能容纳的半分比;   
    自我保护机制的目的是为了所在服务发生严重的网络分区时,依旧能够提供可用性,但为什么要根据心跳作为依据?通过上面的分析我们知道eureka server集群本身是基于http的,无法维持一个持久的状态,在整个系统的网络通信中,在client到server, peer到peer之间,心跳信息应该远大于其他信息的传输量。那虽然peer之间并不根据彼此的心跳(自身也是client)做什么逻辑判断,但其下的client的心跳复制数据本身也足够作为判断分区的依据了。而在一个稳定理想的集群中,心跳的信息绝大多数应该是其他peer复制过来的,如果达到一定阈值,更多的可能性不是server和client发生分区,而是peer和peer之间发生分区,但本身client并没有真的down掉。所以才有这种自我保护的触发机制—— 更高的概率是client可用,该机制通过配置可以关闭 eureka.server.enableSelfPreservation=false

public void evict(long additionalLeaseMs) {
        logger.debug("Running the evict task");

        if (!isLeaseExpirationEnabled()) {
            logger.debug("DS: lease expiration is currently disabled.");
            return;
        }

        // We collect first all expired items, to evict them in random order. For large eviction sets,
        // if we do not that, we might wipe out whole apps before self preservation kicks in. By randomizing it,
        // the impact should be evenly distributed across all applications.
        List<Lease<InstanceInfo>> expiredLeases = new ArrayList<>();
        for (Entry<String, Map<String, Lease<InstanceInfo>>> groupEntry : registry.entrySet()) {
            Map<String, Lease<InstanceInfo>> leaseMap = groupEntry.getValue();
            if (leaseMap != null) {
                for (Entry<String, Lease<InstanceInfo>> leaseEntry : leaseMap.entrySet()) {
                    Lease<InstanceInfo> lease = leaseEntry.getValue();
                    if (lease.isExpired(additionalLeaseMs) && lease.getHolder() != null) {
                        expiredLeases.add(lease);
                    }
                }
            }
        }
--- 此处判断是否开启 isSelfPreservationModeEnable()
 @Override
    public boolean isLeaseExpirationEnabled() {
        if (!isSelfPreservationModeEnabled()) {
            // The self preservation mode is disabled, hence allowing the instances to expire.
            return true;
        }
        return numberOfRenewsPerMinThreshold > 0 && getNumOfRenewsInLastMin() > numberOfRenewsPerMinThreshold;
    }

 

服务集群数据同步

PeerEurekaNodes 类中可以发现有个定时任务具体做什么updatePeerEurekaNodes(...) 更新 peer Eureka Nodes

try {
            updatePeerEurekaNodes(resolvePeerUrls());
            Runnable peersUpdateTask = new Runnable() {
                @Override
                public void run() {
                    try {
                        updatePeerEurekaNodes(resolvePeerUrls());
                    } catch (Throwable e) {
                        logger.error("Cannot update the replica Nodes", e);
                    }

                }
            };
            taskExecutor.scheduleWithFixedDelay(
                    peersUpdateTask,
                    serverConfig.getPeerEurekaNodesUpdateIntervalMs(),
                    serverConfig.getPeerEurekaNodesUpdateIntervalMs(),
                    TimeUnit.MILLISECONDS
            );
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }

源码github https://github.com/zhaoqilong3031/SpringCloud/tree/master/spring-cloud-zuul

转载于:https://my.oschina.net/u/3260714/blog/874731

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值