Eureka client source – client initialization

The process of reading Eureka source code is as follows: first find the dependent JAR file, and finally find DiscoveryClient, which is the core class of the client

Initializing DiscoveryClient This section describes DiscoveryClient in four parts

Initializes the actuator

    private final ScheduledExecutorService scheduler;
    private final ThreadPoolExecutor heartbeatExecutor;
    private final ThreadPoolExecutor cacheRefreshExecutor;
      // Initializes the scheduler with 2 core threads
      scheduler = Executors.newScheduledThreadPool(2.new ThreadFactoryBuilder().
                                                   setNameFormat("DiscoveryClient-%d").
                                                   setDaemon(true).build());
      // Heartbeat actuator, core thread 1, maximum thread can be configured,
      heartbeatExecutor = new ThreadPoolExecutor(1, 
                                                 clientConfig.getHeartbeatExecutorThreadPoolSize(), 
                                                 0, TimeUnit.SECONDS,
                                                 new SynchronousQueue<Runnable>(), 
                                                 new ThreadFactoryBuilder().
                                                 setNameFormat("DiscoveryClient-HeartbeatExecutor-%d").
                                                 setDaemon(true).build()
      ); 
      // Local registry cache flush executor
      cacheRefreshExecutor = new ThreadPoolExecutor(1, 
                                                    clientConfig.getCacheRefreshExecutorThreadPoolSize(), 
                                                    0, TimeUnit.SECONDS,
                                                    new SynchronousQueue<Runnable>(),
                                                    new ThreadFactoryBuilder().
                                                    setNameFormat("DiscoveryClient-CacheRefreshExecutor-%d").
                                                    setDaemon(true).build()
      ); 
Copy the code
  • Obtain the registry from EurekaServer. The default value is true
    // Whether to obtain registration information from EurekaServer
    if (clientConfig.shouldFetchRegistry()) {
      try {
        // Whether to obtain the registration information in full (false is passed to indicate that full retrieval is not mandatory)
        boolean primaryFetchRegistryResult = fetchRegistry(false);
        boolean backupFetchRegistryResult = true;
        FetchRegistryFromBackup ()
        / / fetchRegistryFromBackup (registry) was obtained from the other EuerkaServer or locally
        if(! primaryFetchRegistryResult && ! fetchRegistryFromBackup()) { backupFetchRegistryResult =false;
        }
        If mandatory registration at initialization is set to true, an exception will be raised. The default is false
        if(! primaryFetchRegistryResult && ! backupFetchRegistryResult && clientConfig.shouldEnforceFetchRegistryAtInit()) {throw new IllegalStateException("Fetch registry error at startup. Initial fetch failed."); }}catch (Throwable th) {
      }
    }
Copy the code

The service registry

    // Whether to register with Eureka and enforce registration at initialization
    if (clientConfig.shouldRegisterWithEureka() && clientConfig.shouldEnforceRegistrationAtInit()) {
        // Execute the registration process
        if(! register() ) {throw new IllegalStateException("Registration error at startup. Invalid server response."); }}Copy the code

Initial tasks

    initScheduledTasks();
    private void initScheduledTasks(a) {
      // If you need to obtain registration information from EurekaServer
      if (clientConfig.shouldFetchRegistry()) {
        // Configuration annotations refer to the EurekaClientConfig configuration annotations above
        int registryFetchIntervalSeconds = clientConfig.getRegistryFetchIntervalSeconds();
        int expBackOffBound = clientConfig.getCacheRefreshExecutorExponentialBackOffBound();
        // Local cache task
        cacheRefreshTask = new TimedSupervisorTask("cacheRefresh", 
                                                   scheduler, cacheRefreshExecutor,       
                                                   registryFetchIntervalSeconds, TimeUnit.SECONDS,
                                                   expBackOffBound, new CacheRefreshThread());
        // Schedule the local cache task
        scheduler.schedule(cacheRefreshTask, registryFetchIntervalSeconds, TimeUnit.SECONDS);
      }
      
      // If you need to register to the registry
      if (clientConfig.shouldRegisterWithEureka()) {
        int renewalIntervalInSecs = instanceInfo.getLeaseInfo().getRenewalIntervalInSecs();
        int expBackOffBound = clientConfig.getHeartbeatExecutorExponentialBackOffBound();
        / / the heart Task
        heartbeatTask = new TimedSupervisorTask("heartbeat", 
                                                scheduler, heartbeatExecutor,
                                                renewalIntervalInSecs, TimeUnit.SECONDS, 
                                                expBackOffBound, new HeartbeatThread());
        // Start scheduling heartbeat tasks
        scheduler.schedule(heartbeatTask, renewalIntervalInSecs, TimeUnit.SECONDS);
        InstanceInfo replicator, which implements Runnable interface, mainly updates local InstanceInfo to EurekaServer
        instanceInfoReplicator = new InstanceInfoReplicator(this, instanceInfo, 
          clientConfig.getInstanceInfoReplicationIntervalSeconds(), 2); // burstSize
        // State change listener
        statusChangeListener = new ApplicationInfoManager.StatusChangeListener() {
          @Override
          public String getId(a) {
            return "statusChangeListener";
          }
          @Override
          public void notify(StatusChangeEvent statusChangeEvent) {
            if (InstanceStatus.DOWN == statusChangeEvent.getStatus() ||
                InstanceStatus.DOWN == statusChangeEvent.getPreviousStatus()) {
            }
            // Update instanceInfo after status changesinstanceInfoReplicator.onDemandUpdate(); }};// If set to true, the local InstanceInfo state becomes too small and will be registered or updated to EurekaServer
        if (clientConfig.shouldOnDemandUpdateStatusChange()) {
          applicationInfoManager.registerStatusChangeListener(statusChangeListener);
        }
        // Start, start task scheduling, the task is itself (instanceInfoReplicator) mainly update the local InstanceInfoinstanceInfoReplicator.start(clientConfig.getInitialInstanceInfoReplicationIntervalSeconds()); }}Copy the code

conclusion

  • Initialize EurekaClientConfig: the configuration information about the client
  • Initializing DiscoveryClient core classes is used to obtain registration information, renew, update, and cancel DiscoveryClient core classes
  • Initialize and start the local registry refresh scheduled task, heartbeat scheduled task, instance configuration update scheduled task,
  • And whether to initiate the registration process according to the configuration