Spring Cloud Eureka 作为微服务的注册中心,同时也是AP服务,它有很很强的分区容错性和高可用性。 Eureka提供了服务端和客户端,内部通过定时任务发送心跳机制的方式来维持长时间提供服务。
Eureka-client
其中Eureka-client包中的核心类DiscoveryClient为客户端提供注册和续约。 CacheRefreshThread,定时刷新注册表,30秒执行一次,定时抓取增量注册表到本地;HeartbeatThread,定时发送心跳,30秒执行一次,向 Eureka Server 发送续约请求。
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);
}
Eureka-server
Eureka-server接受心跳请求,通过核心类InstanceResource的renewLease方法
public boolean renew(String appName, String serverId, boolean isReplication) {
this.log(“renew “ + appName + “ serverId “ + serverId + “, isReplication {}” + isReplication);
List<Application> applications = this.getSortedApplications();
Iterator var5 = applications.iterator();
代码中返回的List 获取所有注册的服务列表,通过循环publishEvent发布事件。EurekaServer接收心跳请求是经过InstanceResource的renewLease 方法,先自己接收并处理来自 EurekaClient心跳,后将该心跳同步至 EurekaServer 集群中的其它节点。
EurekaServer 在初始化的时候会启动一个EvictionTask 定时任务,默认每分钟检查一次心跳收集情况,并对长时间没有心跳的服务实例执行过期处理,默认一分钟一次。
protected void postInit() {
this.renewsLastMin.start();
if (this.evictionTaskRef.get() != null) {
((AbstractInstanceRegistry.EvictionTask)this.evictionTaskRef.get()).cancel();
}
this.evictionTaskRef.set(new AbstractInstanceRegistry.EvictionTask());
this.evictionTimer.schedule((TimerTask)this.evictionTaskRef.get(), this.serverConfig.getEvictionIntervalTimerInMs(), this.serverConfig.getEvictionIntervalTimerInMs());
}
public long getEvictionIntervalTimerInMs() {
return configInstance.getLongProperty(this.namespace + “evictionIntervalTimerInMs”, 60000L).get();
}
总结:
Eureka 作为注册中心整体的运行机制,服务注册、抓取注册表、续约、下线、定时剔除故障实例等一整套机制