SpringCloud源码剖析-Eureka Client服务注册

简介: 程序启动EurekaClientAutoConfiguration被加载,EurekaClient在EurekaClientAutoConfiguration 中通过“延迟@Lazy”注册。同时EurekaAutoServiceRegistration 监听启动事件,调用 EurekaServiceRegistry的register方法进行注册,该方法会触发EurekaClient的创建 。

前言

文章过长,您需要有些耐心!!!

在上一章《Eureka Client 初始化过程》中我们了解到,应用程序在启动的时候就会初始化Eureka并触发Eureka的自动注册,最终会调用DiscoveryClient进行服务注册,我们来跟踪一下DiscoveryClient是如何实现服务注册与发现的。

1.DiscoveryClient 初始化定时任务

程序启动EurekaClientAutoConfiguration被加载,EurekaClient在EurekaClientAutoConfiguration 中通过“延迟@Lazy”注册。同时EurekaAutoServiceRegistration 监听启动事件,调用 EurekaServiceRegistry的register方法进行注册,该方法会触发EurekaClient的创建 。自动配置类中有如下代码

//可刷新的Eureka客户端配置@Configuration@ConditionalOnRefreshScopeprotectedstaticclassRefreshableEurekaClientConfiguration {
@AutowiredprivateApplicationContextcontext;
@AutowiredprivateAbstractDiscoveryClientOptionalArgs<?>optionalArgs;
//注册EurekaClient@Bean(destroyMethod="shutdown")
@ConditionalOnMissingBean(value=EurekaClient.class, search=SearchStrategy.CURRENT)
@org.springframework.cloud.context.config.annotation.RefreshScope@LazypublicEurekaClienteurekaClient(ApplicationInfoManagermanager, EurekaClientConfigconfig, EurekaInstanceConfiginstance) {
//初始化InstanceInfo,服务实例注册信息对象manager.getInfo(); // force initialization//创建CloudEurekaClient ,他是 EurekaClient的实现类returnnewCloudEurekaClient(manager, config, this.optionalArgs,
this.context);
    }
    ...省略...

这里初始化InstanceInfo服务注册实例之后,创建了EurekaClient 客户端,通过子类 CloudEurekaClient进行创建,只不过这里是@Lazy延迟创建,在,跟踪下去,我们看一下CloudEurekaClient是如何创建的

publicclassCloudEurekaClientextendsDiscoveryClient {
    ...省略...
privateApplicationInfoManagerapplicationInfoManager;
privateAtomicReference<EurekaHttpClient>eurekaHttpClient=newAtomicReference<>();
publicCloudEurekaClient(ApplicationInfoManagerapplicationInfoManager,
EurekaClientConfigconfig, ApplicationEventPublisherpublisher) {
this(applicationInfoManager, config, null, publisher);
    }
//创建CloudEurekaClient的构造器publicCloudEurekaClient(ApplicationInfoManagerapplicationInfoManager,
EurekaClientConfigconfig,
AbstractDiscoveryClientOptionalArgs<?>args,
ApplicationEventPublisherpublisher) {
//通过父类DiscoveryClient进行初始化super(applicationInfoManager, config, args);
this.applicationInfoManager=applicationInfoManager;
this.publisher=publisher;
this.eurekaTransportField=ReflectionUtils.findField(DiscoveryClient.class, "eurekaTransport");
ReflectionUtils.makeAccessible(this.eurekaTransportField);
    }

这里super(applicationInfoManager, config, args);通过父类初始化他的父类是DiscoveryClient,DiscoveryClient的父接口是EurekaClient

我们继续跟踪上去DiscoveryClient的构造器

@InjectDiscoveryClient(ApplicationInfoManagerapplicationInfoManager, EurekaClientConfigconfig, AbstractDiscoveryClientOptionalArgsargs,
Provider<BackupRegistry>backupRegistryProvider) {
if (args!=null) {
//健康检查处理器this.healthCheckHandlerProvider=args.healthCheckHandlerProvider;
//健康检查回调this.healthCheckCallbackProvider=args.healthCheckCallbackProvider;
this.eventListeners.addAll(args.getEventListeners());
this.preRegistrationHandler=args.preRegistrationHandler;
    } else {
this.healthCheckCallbackProvider=null;
this.healthCheckHandlerProvider=null;
this.preRegistrationHandler=null;
    }
//InstanceInfo管理器this.applicationInfoManager=applicationInfoManager;
//InstanceInfo服务实例注册信息,注册的对象InstanceInfomyInfo=applicationInfoManager.getInfo();
//eureka客户端配置clientConfig=config;
staticClientConfig=clientConfig;
//和eurekaServrer的通信配置,该配置通过EurekaClientConfigBean来创建transportConfig=config.getTransportConfig();
instanceInfo=myInfo;
if (myInfo!=null) {
appPathIdentifier=instanceInfo.getAppName() +"/"+instanceInfo.getId();
    } else {
logger.warn("Setting instanceInfo to a passed in null value");
    }
//备份注册表this.backupRegistryProvider=backupRegistryProvider;
this.urlRandomizer=newEndpointUtils.InstanceInfoBasedUrlRandomizer(instanceInfo);
localRegionApps.set(newApplications());
fetchRegistryGeneration=newAtomicLong(0);
remoteRegionsToFetch=newAtomicReference<String>(clientConfig.fetchRegistryForRemoteRegions());
remoteRegionsRef=newAtomicReference<>(remoteRegionsToFetch.get() ==null?null : remoteRegionsToFetch.get().split(","));
//注册表过时监控if (config.shouldFetchRegistry()) {
this.registryStalenessMonitor=newThresholdLevelsMetric(this, METRIC_REGISTRY_PREFIX+"lastUpdateSec_", newlong[]{15L, 30L, 60L, 120L, 240L, 480L});
    } else {
this.registryStalenessMonitor=ThresholdLevelsMetric.NO_OP_METRIC;
    }
//心跳监控if (config.shouldRegisterWithEureka()) {
this.heartbeatStalenessMonitor=newThresholdLevelsMetric(this, METRIC_REGISTRATION_PREFIX+"lastHeartbeatSec_", newlong[]{15L, 30L, 60L, 120L, 240L, 480L});
    } else {
this.heartbeatStalenessMonitor=ThresholdLevelsMetric.NO_OP_METRIC;
    }
logger.info("Initializing Eureka in region {}", clientConfig.getRegion());
//如果不注册,不拉取注册列表,置空相关的定时任务以及相关配置if (!config.shouldRegisterWithEureka() &&!config.shouldFetchRegistry()) {
logger.info("Client configured to neither register nor query for data.");
scheduler=null;
heartbeatExecutor=null;
cacheRefreshExecutor=null;
eurekaTransport=null;
instanceRegionChecker=newInstanceRegionChecker(newPropertyBasedAzToRegionMapper(config), clientConfig.getRegion());
// This is a bit of hack to allow for existing code using DiscoveryManager.getInstance()// to work with DI'd DiscoveryClientDiscoveryManager.getInstance().setDiscoveryClient(this);
DiscoveryManager.getInstance().setEurekaClientConfig(config);
initTimestampMs=System.currentTimeMillis();
logger.info("Discovery Client initialized at timestamp {} with initial instances count: {}",
initTimestampMs, this.getApplications().size());
return;  // no need to setup up an network tasks and we are done    }
try {
//初始化线程池======================================//创建定时任务执行器,核心数2// default size of 2 - 1 each for heartbeat and cacheRefreshscheduler=Executors.newScheduledThreadPool(2,
newThreadFactoryBuilder()
                                                     .setNameFormat("DiscoveryClient-%d")
                                                     .setDaemon(true)
                                                     .build());
//带线程池的执行器,心跳线程池执行器heartbeatExecutor=newThreadPoolExecutor(
1, clientConfig.getHeartbeatExecutorThreadPoolSize(), 0, TimeUnit.SECONDS,
newSynchronousQueue<Runnable>(),
newThreadFactoryBuilder()
            .setNameFormat("DiscoveryClient-HeartbeatExecutor-%d")
            .setDaemon(true)
            .build()
        );  // use direct handoff//刷新服务列表缓存线程执行器cacheRefreshExecutor=newThreadPoolExecutor(
1, clientConfig.getCacheRefreshExecutorThreadPoolSize(), 0, TimeUnit.SECONDS,
newSynchronousQueue<Runnable>(),
newThreadFactoryBuilder()
            .setNameFormat("DiscoveryClient-CacheRefreshExecutor-%d")
            .setDaemon(true)
            .build()
        );  // use direct handoff//初始化和EurekaServer交互的客户端EurekaHttpClient,//会创建服务注册的EurekaHttpClient和拉取注册表的EurekaHttpClienteurekaTransport=newEurekaTransport();
scheduleServerEndpointTask(eurekaTransport, args);
AzToRegionMapperazToRegionMapper;
if (clientConfig.shouldUseDnsForFetchingServiceUrls()) {
azToRegionMapper=newDNSBasedAzToRegionMapper(clientConfig);
        } else {
azToRegionMapper=newPropertyBasedAzToRegionMapper(clientConfig);
        }
if (null!=remoteRegionsToFetch.get()) {
azToRegionMapper.setRegionsToFetch(remoteRegionsToFetch.get().split(","));
        }
instanceRegionChecker=newInstanceRegionChecker(azToRegionMapper, clientConfig.getRegion());
    } catch (Throwablee) {
thrownewRuntimeException("Failed to initialize DiscoveryClient!", e);
    }
//从来备份中拉取注册表,底层没做实现if (clientConfig.shouldFetchRegistry() &&!fetchRegistry(false)) {
fetchRegistryFromBackup();
    }
// call and execute the pre registration handler before all background tasks (inc registration) is startedif (this.preRegistrationHandler!=null) {
this.preRegistrationHandler.beforeRegistration();
    }
//如果开启服务注册 if (clientConfig.shouldRegisterWithEureka() &&clientConfig.shouldEnforceRegistrationAtInit()) {
try {
//调用register()方法发起服务注册 ,默认 clientConfig.shouldEnforceRegistrationAtInit是不满足的if (!register() ) {
thrownewIllegalStateException("Registration error at startup. Invalid server response.");
            }
        } catch (Throwableth) {
logger.error("Registration error at startup: {}", th.getMessage());
thrownewIllegalStateException(th);
        }
    }
//初始化定时任务// finally, init the schedule tasks (e.g. cluster resolvers, heartbeat, instanceInfo replicator, fetchinitScheduledTasks();
try {
//监视注册表Monitors.registerObject(this);
    } catch (Throwablee) {
logger.warn("Cannot register timers", e);
    }
// This is a bit of hack to allow for existing code using DiscoveryManager.getInstance()// to work with DI'd DiscoveryClientDiscoveryManager.getInstance().setDiscoveryClient(this);
DiscoveryManager.getInstance().setEurekaClientConfig(config);
initTimestampMs=System.currentTimeMillis();
logger.info("Discovery Client initialized at timestamp {} with initial instances count: {}",
initTimestampMs, this.getApplications().size());
}

构造器中做了一些初始化工作

  • 比如初始化心跳线程执行器,服务列表刷新线程执行器
  • 比如创建EurekaTransport,用来和Eureka交互的客户端,内部创建了EurekaHttpClient来发请求
  • 最后调用initScheduledTasks方法进行定时任务的初始化

2.initScheduledTasks初始化定时任务

接下来我们详细看一下initScheduledTasks中的代码:

/**初始化所有定时任务* Initializes all scheduled tasks.*/privatevoidinitScheduledTasks() {
//判断如果要拉取注册表if (clientConfig.shouldFetchRegistry()) {
//刷新注册表的心跳时间间隔// registry cache refresh timerintregistryFetchIntervalSeconds=clientConfig.getRegistryFetchIntervalSeconds();
intexpBackOffBound=clientConfig.getCacheRefreshExecutorExponentialBackOffBound();
//刷新注册表的定时任务:CacheRefreshThread刷新注册表scheduler.schedule(
newTimedSupervisorTask(
"cacheRefresh",
scheduler,
cacheRefreshExecutor,
registryFetchIntervalSeconds,
TimeUnit.SECONDS,
expBackOffBound,
newCacheRefreshThread()
            ),
registryFetchIntervalSeconds, TimeUnit.SECONDS);
    }
//是否要注册到Eureakaif (clientConfig.shouldRegisterWithEureka()) {
//这里取的是租约更新时间 30s/次intrenewalIntervalInSecs=instanceInfo.getLeaseInfo().getRenewalIntervalInSecs();
intexpBackOffBound=clientConfig.getHeartbeatExecutorExponentialBackOffBound();
logger.info("Starting heartbeat executor: "+"renew interval is: {}", renewalIntervalInSecs);
// Heartbeat timer//心跳续约的定时任务 :HeartbeatThread 中进行续约,内部调用DiscoverClient.renew方法scheduler.schedule(
newTimedSupervisorTask(
"heartbeat",
scheduler,
heartbeatExecutor,
renewalIntervalInSecs,
TimeUnit.SECONDS,
expBackOffBound,
newHeartbeatThread()
            ),
renewalIntervalInSecs, TimeUnit.SECONDS);
// InstanceInfo replicator//注册实例InstanceInfo的复制器,负责将自身的信息周期性的上报到EurekaServer;//,内部会通过定时任务调用(赋值时间40s间隔),检查InstanceInfo(DataCenterInfo,LeaseInfo,InstanceStatus)是否有变化,//内部调用InstanceInfoReplicator.run方法,再调用Discoverlient.refreshInstanceInfo()方法通过ApplicationInfoManager刷新实例状态//刷新完成后会调用 discoveryClient.register();进行注册instanceInfoReplicator=newInstanceInfoReplicator(
this,
instanceInfo,
//定时调度时间间隔,30s/次clientConfig.getInstanceInfoReplicationIntervalSeconds(),
2); // burstSize//创建注册状态改变监听statusChangeListener=newApplicationInfoManager.StatusChangeListener() {
@OverridepublicStringgetId() {
return"statusChangeListener";
            }
@Overridepublicvoidnotify(StatusChangeEventstatusChangeEvent) {
if (InstanceStatus.DOWN==statusChangeEvent.getStatus() ||InstanceStatus.DOWN==statusChangeEvent.getPreviousStatus()) {
// log at warn level if DOWN was involvedlogger.warn("Saw local status change event {}", statusChangeEvent);
                } else {
logger.info("Saw local status change event {}", statusChangeEvent);
                }
//按需更新,使用scheduler执行一个Runnable任务,任务中调用InstanceInfoReplicator.this.run()方法,//run方法中先执行discoveryClient.refreshInstanceInfo();刷新实例状态,//然后调用discoveryClient.register()注册,如果在DiscoveryClient初始化的时候,instanceInfoReplicator.onDemandUpdate();
            }
        };
//通过applicationInfoManager注册监听器if (clientConfig.shouldOnDemandUpdateStatusChange()) {
applicationInfoManager.registerStatusChangeListener(statusChangeListener);
        }
//启动InstanceInfo复制器,传入 复制实例的时间间隔instanceInfoReplicator.start(clientConfig.getInitialInstanceInfoReplicationIntervalSeconds());
    } else {
logger.info("Not registering with Eureka server per configuration");
    }
}

总结一下initScheduledTasks做了如下事情

  • 启动线程调用CacheRefreshThread任务刷新服务列表(registryFetchIntervalSeconds=30s执行一次),从EurekaServer拉取服务注册列表同时刷新客户端缓存
  • 启动heartbeat心跳定时线程(renewalIntervalInSecs=30s续约一次)执行任务HeartbeatThread,调用DiscoverClient.renew定时向Eureka Server发送心跳
  • 启动InstanceInfo复制器定时线程,开启定时线程检查当前检查DataCenterInfo,LeaseInfo,InstanceStatus状态,内部通过isInstanceInfoDirty属性来标记是否有状态改变,如果发现变更就执行discoveryClient.register()将实例信息同步到Server端实现服务注册
  • 通过ApplicationInfoManager注册了StatusChangeListener来监听服务的注册状态改变,当服务状态改变会调用ApplicationInfoManager.setInstanceStatus方法设置服务状态会触发StatusChangeListener监听器,该监听器会调用instanceInfoReplicator.onDemandUpdate();进行按需更新,内部会检查服务变更信息,如果有变更,然后把服务信息注册到Eureaka

需要补充说明的是:在Eureka启动时会自动注册,在EurekaServiceRegistry.register方法会注册EurekaRegistration,方法中会初始化EurekaClient(DiscoveryClient创建)从而注册ApplicationInfoManager中的StatusChangeListener,初始化完成之后会接着执行reg.getApplicationInfoManager().setInstanceStatus(reg.getInstanceConfig().getInitialStatus());修改ApplicationInfoManager中的InstatceStatus状态为UP,ApplicationInfoManager在EurekaClientAutoConfiguration中被创建的时候,里面的InstanceInfo是通过new InstanceInfoFactory().create(config);创建,其中的InstanceStatus默认是STARING,这个状态的改变会触发StatusChangeListener监听器的执行从而触发StatusChangeListener

3.InstanceInfoReplicator复制InstanceInfo注册服务

在initScheduledTasks方法中通过InstanceInfoReplicator复制服务实例,然后调用DiscoverClient.register进行注册

classInstanceInfoReplicatorimplementsRunnable {
...省略...
//在DiscoverClient初始化的时候调用 延迟40s执行publicvoidstart(intinitialDelayMs) {
if (started.compareAndSet(false, true)) {
//标记实例有更新(脏数据),这个标记是服务注册的依据instanceInfo.setIsDirty();  // for initial register//定时调度,30s/次Futurenext=scheduler.schedule(this, initialDelayMs, TimeUnit.SECONDS);   
scheduledPeriodicRef.set(next);
        }
    }
    ...省略...
//按需更新,会定时触发服务状态检查和服务注册,见Run方法publicbooleanonDemandUpdate() {
if (rateLimiter.acquire(burstSize, allowedRatePerMinute)) {
//定时执行if (!scheduler.isShutdown()) {
scheduler.submit(newRunnable() {
@Overridepublicvoidrun() {
logger.debug("Executing on-demand update of local InstanceInfo");
FuturelatestPeriodic=scheduledPeriodicRef.get();
if (latestPeriodic!=null&&!latestPeriodic.isDone()) {
logger.debug("Canceling the latest scheduled update, it will be rescheduled at the end of on demand update");
latestPeriodic.cancel(false);
                        }
//调用run方法InstanceInfoReplicator.this.run();
                    }
                });
returntrue;
            } else {
logger.warn("Ignoring onDemand update due to stopped scheduler");
returnfalse;
            }
        } else {
logger.warn("Ignoring onDemand update due to rate limiter");
returnfalse;
        }
    }
publicvoidrun() {
try {
//刷新InstanceInfo,内部会检查:dataCenter和 LeaseInfo//applicationInfoManager.refreshDataCenterInfoIfRequired();//applicationInfoManager.refreshLeaseInfoIfRequired();//根据HealthCheckHandler获取实例状态InstanceStatus,并更新,如果状态发生变化会触发所有StatusChangeListenerdiscoveryClient.refreshInstanceInfo();
//刷新后,如果实例发生了变更(有脏数据),就发起注册LongdirtyTimestamp=instanceInfo.isDirtyWithTime();
if (dirtyTimestamp!=null) {
//发起注册discoveryClient.register();
instanceInfo.unsetIsDirty(dirtyTimestamp);
            }
        } catch (Throwablet) {
logger.warn("There was a problem with the instance info replicator", t);
        } finally {
Futurenext=scheduler.schedule(this, replicationIntervalSeconds, TimeUnit.SECONDS);
scheduledPeriodicRef.set(next);
        }
    }

InstanceInfoReplicator的run方法会在2个地方被调用,一是会在DiscoverClient初始化定时任务initScheduledTasks方法中被创建调用instanceInfoReplicator.start 延迟40s执行,而是调用ApplicationInfoManager.setInstanceStatus改变了实例状态,触发StatusChangeListener监听器,在监听器内部会触发InstanceInfoReplicator.onDemandUpdate方法,然后调用run方法。

4.DiscoveryClient.register服务注册

通过上面的源码跟踪我们知道,Eureka通过DiscoverClient发起服务注册

/*** Register with the eureka service by making the appropriate REST call.*/booleanregister() throwsThrowable {
logger.info(PREFIX+"{}: registering service...", appPathIdentifier);
//http响应EurekaHttpResponse<Void>httpResponse;
try {
//提交注册,发起http请求,eurekaTransport是在DiscoveryClient初始化的时候创建的和EurekaServer交互的客户端,这里是把InstanceInfo作为注册实例提交到EurekaServerhttpResponse=eurekaTransport.registrationClient.register(instanceInfo);
        } catch (Exceptione) {
logger.warn(PREFIX+"{} - registration failed {}", appPathIdentifier, e.getMessage(), e);
throwe;
        }
if (logger.isInfoEnabled()) {
logger.info(PREFIX+"{} - registration status: {}", appPathIdentifier, httpResponse.getStatusCode());
        }
returnhttpResponse.getStatusCode() ==204;
    }

这里通过调用:eurekaTransport.registrationClient.register(instanceInfo);得到一个EurekaHttpClient,然后调用register方法向EurekaServer发起http请求实现注册,eurekaTransport是在DiscoveryClient初始化的时候创建的和EurekaServer交互的客户端,这里是把InstanceInfo作为注册实例提交到EurekaServer,继续跟踪下去

publicabstractclassEurekaHttpClientDecoratorimplementsEurekaHttpClient {
@OverridepublicEurekaHttpResponse<Void>register(finalInstanceInfoinfo) {
returnexecute(newRequestExecutor<Void>() {
@OverridepublicEurekaHttpResponse<Void>execute(EurekaHttpClientdelegate) {
//发起注册请求returndelegate.register(info);
            }
@OverridepublicRequestTypegetRequestType() {
returnRequestType.Register;
            }
        });
    }

代码执行到EurekaHttpClient的装饰类EurekaHttpClientDecorator,先后会执行RetryableEurekaHttpClient(Http请求失败进行重试),

RedirectingEurekaHttpClient(重定向到不同的EurekaServer)

MetricsCollectingEurekaHttpClient(统计执行指标)

AbstractJerseyEurekaHttpClient(使用jersey发起注册)

继续跟踪,会调用AbstractJerseyEurekaHttpClient的register方法注册

publicabstractclassAbstractJerseyEurekaHttpClientimplementsEurekaHttpClient {
@OverridepublicEurekaHttpResponse<Void>register(InstanceInfoinfo) {
StringurlPath="apps/"+info.getAppName();
ClientResponseresponse=null;
try {
//jerseyClient其实是ApacheHttpClientBuilderresourceBuilder=jerseyClient.resource(serviceUrl).path(urlPath).getRequestBuilder();
addExtraHeaders(resourceBuilder);
response=resourceBuilder                .header("Accept-Encoding", "gzip")
                .type(MediaType.APPLICATION_JSON_TYPE)
                .accept(MediaType.APPLICATION_JSON)
                .post(ClientResponse.class, info);
returnanEurekaHttpResponse(response.getStatus()).headers(headersOf(response)).build();
        } finally {
if (logger.isDebugEnabled()) {
logger.debug("Jersey HTTP POST {}/{} with instance {}; statusCode={}", serviceUrl, urlPath, info.getId(),
response==null?"N/A" : response.getStatus());
            }
if (response!=null) {
response.close();
            }
        }
    }

看到这里我们应该就明白了,在register方法中获取到了 serviceUrl 即配置文件中的注册服务地址,把InstanceInfo作为参数,底层通过jersey(rest)来发请求然后会调用WebResource发送post请求,实现服务注册。

publicclassWebResourceextendsFilterableimplementsRequestBuilder<WebResource.Builder>, UniformInterface {
//发送post请求public<T>Tpost(Class<T>c, ObjectrequestEntity) throwsUniformInterfaceException, ClientHandlerException {
returnWebResource.this.handle(c, this.build("POST", requestEntity));
    }
    ....省略....

5.服务注册流程总结

1.程序启动触发EurekaServiceRegistry.register(EurekaRegistration)实现服务自动注册

  • 该方法中会初始化DiscoveryClient,
  • 同时改变ApplicationInfoManager中的InstanceStatus的状态为UP,该状态默认是STARING,该状态的变更会触发StatusChangeListener监听器
  • 给EurekaRegistration.eurekaClient注册了监控检查处理器healthCheckHandler

2.DiscoveryClient初始化流程(构造器)中

  • 创建了心跳线程执行器,服务列表刷新线程执行器,
  • 创建了EurekaTransport(EurekaHttpClient)用来向EureakServer发请求的客户端,
  • 然后调用initScheduledTask初始化定时任务

3.DiscoveryClient.initScheduledTasks方法中

  • 初始化了刷新注册表的定时任务(CacheRefreshThread),
  • 服务心跳心跳定时任务(HeartbeatThread),
  • 创建了InstanceInfoReplicator实例信息复制器,
  • 还注册了ApplicationInfoManager.StatusChangeListener
  • 最后启动InstanceInfoReplicator复制器

4.InstanceInfoReplicator复制InstanceInfo注册服务

  • 首先它是一个Runnable 线程,30s定时调度一次,除了在DiscoveryClient.initScheduledTasks中会被触发调用,会被StatusChangeListener监听器中被调用InstanceInfoReplicator.onDemandUpdate(),
  • 在InstanceInfoReplicator的run方法中会调用discoveryClient.refreshInstanceInfo();先检查实例信息是否有变更,如果有变更(通过instanceInfo.setIsDirty()标记)会向Eureak注册,调用discoveryClient.register();进行注册

4.DiscoveryClient.register服务注册

  • 使用的是eurekaTransport获取一个EurekaHttpClient,调用register方法
  • 最终调用AbstractJerseyEurekaHttpClient中的register,发起http把InstanceInfo注册到EureakServer
目录
相关文章
|
负载均衡 算法 Java
【SpringCloud(4)】OpenFeign客户端:OpenFeign服务绑定;调用服务接口;Feign和OpenFeign
Feign是一个WebService客户端。使用Feign能让编写WebService客户端更加简单。 它的使用方法是定义一个服务接口然后再上面添加注解。Feign也支持可拔插式的编码器和解码器。SpringCloud对Feign进行了封装,十七支持了SpringMVC标准注解和HttpMessageConverters。 Feign可用于Eureka和Ribbon组合使用以支持负载均衡
1186 139
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
1791 3
|
负载均衡 Java API
《深入理解Spring》Spring Cloud 构建分布式系统的微服务全家桶
Spring Cloud为微服务架构提供一站式解决方案,涵盖服务注册、配置管理、负载均衡、熔断限流等核心功能,助力开发者构建高可用、易扩展的分布式系统,并持续向云原生演进。
|
存储 数据可视化 Java
基于MicrometerTracing门面和Zipkin实现集成springcloud2023的服务追踪
Sleuth将会停止维护,Sleuth最新版本也只支持springboot2。作为替代可以使用MicrometerTracing在微服务中作为服务追踪的工具。
1077 2
|
Cloud Native Java Nacos
springcloud/springboot集成NACOS 做注册和配置中心以及nacos源码分析
通过本文,我们详细介绍了如何在 Spring Cloud 和 Spring Boot 中集成 Nacos 进行服务注册和配置管理,并对 Nacos 的源码进行了初步分析。Nacos 作为一个强大的服务注册和配置管理平台,为微服务架构提供
5341 14
|
负载均衡 Dubbo Java
Spring Cloud Alibaba与Spring Cloud区别和联系?
Spring Cloud Alibaba与Spring Cloud区别和联系?
|
前端开发 Java Nacos
🛡️Spring Boot 3 整合 Spring Cloud Gateway 工程实践
本文介绍了如何使用Spring Cloud Alibaba 2023.0.0.0技术栈构建微服务网关,以应对微服务架构中流量治理与安全管控的复杂性。通过一个包含鉴权服务、文件服务和主服务的项目,详细讲解了网关的整合与功能开发。首先,通过统一路由配置,将所有请求集中到网关进行管理;其次,实现了限流防刷功能,防止恶意刷接口;最后,添加了登录鉴权机制,确保用户身份验证。整个过程结合Nacos注册中心,确保服务注册与配置管理的高效性。通过这些实践,帮助开发者更好地理解和应用微服务网关。
2827 0
🛡️Spring Boot 3 整合 Spring Cloud Gateway 工程实践
|
监控 JavaScript 数据可视化
建筑施工一体化信息管理平台源码,支持微服务架构,采用Java、Spring Cloud、Vue等技术开发。
智慧工地云平台是专为建筑施工领域打造的一体化信息管理平台,利用大数据、云计算、物联网等技术,实现施工区域各系统数据汇总与可视化管理。平台涵盖人员、设备、物料、环境等关键因素的实时监控与数据分析,提供远程指挥、决策支持等功能,提升工作效率,促进产业信息化发展。系统由PC端、APP移动端及项目、监管、数据屏三大平台组成,支持微服务架构,采用Java、Spring Cloud、Vue等技术开发。
863 7
|
人工智能 安全 Java
AI 时代:从 Spring Cloud Alibaba 到 Spring AI Alibaba
本次分享由阿里云智能集团云原生微服务技术负责人李艳林主讲,主题为“AI时代:从Spring Cloud Alibaba到Spring AI Alibaba”。内容涵盖应用架构演进、AI agent框架发展趋势及Spring AI Alibaba的重磅发布。分享介绍了AI原生架构与传统架构的融合,强调了API优先、事件驱动和AI运维的重要性。同时,详细解析了Spring AI Alibaba的三层抽象设计,包括模型支持、工作流智能体编排及生产可用性构建能力,确保安全合规、高效部署与可观测性。最后,结合实际案例展示了如何利用私域数据优化AI应用,提升业务价值。
2143 4