当前位置:网站首页>Instanceinforeplicator class of Eureka (service registration auxiliary class)

Instanceinforeplicator class of Eureka (service registration auxiliary class)

2022-06-22 13:45:00 51CTO

Welcome to visit mine GitHub

Here we classify and summarize all the original works of Xinchen ( Including supporting source code ): https://github.com/zq2599/blog_demos

About service registration

  • The following pictures are from  Netflix official , The picture shows Eureka Client Will initiate... To the registry Get Registry Request to get the list of services :

Eureka Of InstanceInfoReplicator class ( Service registration auxiliary class )_SpringCloud

  • With Spring Cloud Of Edgware.RELEASE Version as an example ,Eureka client The registration action of is on the com.netflix.discovery.DiscoveryClient Class initScheduledTasks Method , The relevant code snippet is shown below , Please pay attention to the Chinese Notes :
// Omit irrelevant code 
...
// Instantiation InstanceInfoReplicator object 
instanceInfoReplicator = new InstanceInfoReplicator(
                    this,
                    instanceInfo,
                    clientConfig.getInstanceInfoReplicationIntervalSeconds(),
                    2); // burstSize

            // Monitor , Used to monitor as Eureka client The state of oneself changes 
            statusChangeListener = new ApplicationInfoManager.StatusChangeListener() {
                @Override
                public String getId() {
                    return "statusChangeListener";
                }

                @Override
                public void notify(StatusChangeEvent statusChangeEvent) {
                    if (InstanceStatus.DOWN == statusChangeEvent.getStatus() ||
                            InstanceStatus.DOWN == statusChangeEvent.getPreviousStatus()) {
                        // log at warn level if DOWN was involved
                        logger.warn("Saw local status change event {}", statusChangeEvent);
                    } else {
                        logger.info("Saw local status change event {}", statusChangeEvent);
                    }
                    // When the state changes notify Methods will be executed , Report the latest status to Eureka server
                    instanceInfoReplicator.onDemandUpdate();
                }
            };

            if (clientConfig.shouldOnDemandUpdateStatusChange()) {
                // Register listener 
                applicationInfoManager.registerStatusChangeListener(statusChangeListener);
            }
            // Service registration 
            instanceInfoReplicator.start(clientConfig.getInitialInstanceInfoReplicationIntervalSeconds());

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • The above code indicates that , Report your information to Eureka server Your job is to call instanceInfoReplicator Of api Accomplished ;

InstanceInfoReplicator The role of

  • First look at InstanceInfoReplicator Comments on source code :
/** * A task for updating and replicating the local instanceinfo to the remote server. Properties of this task are: * - configured with a single update thread to guarantee sequential update to the remote server * - update tasks can be scheduled on-demand via onDemandUpdate() * - task processing is rate limited by burstSize * - a new update task is always scheduled automatically after an earlier update task. However if an on-demand task * is started, the scheduled automatic update task is discarded (and a new one will be scheduled after the new * on-demand update). * * @author dliu */

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • I understand it :
  1. InstanceInfoReplicator It is a task class , Be responsible for periodically reporting their own information to Eureka server;
  2. There are two scenarios that trigger escalation : Periodic tasks 、 Service status changes (onDemandUpdate Called ), therefore , There may be two tasks reported at the same time ;
  3. A single thread executes the reported operation , If there are multiple reporting tasks , It can also ensure that it is serial ;
  4. There's a frequency limit , adopt burstSize Parameters to control ;
  5. Tasks created first are always executed first , however onDemandUpdate The task created in the method discards the periodic task ;

Source code analysis

  • The previous understanding of annotation is the main line , Go to the source code :
  • First look at the construction method , as follows , Note the position of Chinese notes :
InstanceInfoReplicator(DiscoveryClient discoveryClient, InstanceInfo instanceInfo, int replicationIntervalSeconds, int burstSize) {
        this.discoveryClient = discoveryClient;
        this.instanceInfo = instanceInfo;
		// Thread pool ,core size by 1, Use DelayedWorkQueue queue 
        this.scheduler = Executors.newScheduledThreadPool(1,
                new ThreadFactoryBuilder()
                        .setNameFormat("DiscoveryClient-InstanceInfoReplicator-%d")
                        .setDaemon(true)
                        .build());

        this.scheduledPeriodicRef = new AtomicReference<Future>();

        this.started = new AtomicBoolean(false);
        //RateLimiter Is a tool class that limits frequency , Used to limit the number of tasks per unit time 
        this.rateLimiter = new RateLimiter(TimeUnit.MINUTES);
        this.replicationIntervalSeconds = replicationIntervalSeconds;
        this.burstSize = burstSize;
        // Through the cycle interval , and burstSize Parameters , Calculate the number of tasks allowed per minute 
        this.allowedRatePerMinute = 60 * this.burstSize / this.replicationIntervalSeconds;
        logger.info("InstanceInfoReplicator onDemand update allowed rate per min is {}", allowedRatePerMinute);
    }

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • As can be seen from the above code , The line path pool and frequency limiting tool are prepared in the construction method , Calculate the number of tasks allowed per minute ;
  • stay com.netflix.discovery.DiscoveryClient Class initScheduledTasks In the method , By calling instanceInfoReplicator.start Method starts the periodic task , Now let's look at this method :
public void start(int initialDelayMs) {
		//CAS operation , Not only does it ensure that it is executed only once , Multithreading scenarios can also guarantee 
		if (started.compareAndSet(false, true)) {
		        instanceInfo.setIsDirty();  // for initial register
		        // Submit a task , Delayed execution , Notice that the first parameter is this, So at the end of the delay ,InstanceInfoReplicator Of run Methods will be executed 
		        Future next = scheduler.schedule(this, initialDelayMs, TimeUnit.SECONDS);
		        // For this task Feature Put the object in the member variable scheduledPeriodicRef in 
		        scheduledPeriodicRef.set(next);
		}
}

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • When the delay time arrives , Will execute run Method :
public void run() {
        try {
            // Update the information , For later escalation 
            discoveryClient.refreshInstanceInfo();

            Long dirtyTimestamp = instanceInfo.isDirtyWithTime();
            if (dirtyTimestamp != null) {
                // Report 
                discoveryClient.register();
                instanceInfo.unsetIsDirty(dirtyTimestamp);
            }
        } catch (Throwable t) {
            logger.warn("There was a problem with the instance info replicator", t);
        } finally {
            // A delayed task will be created after each execution , In this way, the logic of periodic execution is realized 
            Future next = scheduler.schedule(this, replicationIntervalSeconds, TimeUnit.SECONDS);
            // Every time a recurring task is created , All of them scheduledPeriodicRef,
            // If an external call onDemandUpdate, You can pass onDemandUpdate Get the current task to perform 
            scheduledPeriodicRef.set(next);
        }
    }

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • Sum up the above codes , The logic of periodic tasks is completed , Next, let's look at the externally invoked onDemandUpdate Method :
public boolean onDemandUpdate() {
        // The frequency limit is not reached 
        if (rateLimiter.acquire(burstSize, allowedRatePerMinute)) {
            // Submit a task 
            scheduler.submit(new Runnable() {
                @Override
                public void run() {
                    logger.debug("Executing on-demand update of local InstanceInfo");
                    // Take out the previously submitted tasks 
                    Future latestPeriodic = scheduledPeriodicRef.get();
                    // If this task is not completed , Immediately cancel 
                    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);
                    }
					// By calling run Method , Make the task execute after delay , Equivalent to one of the periodic tasks 
                    InstanceInfoReplicator.this.run();
                }
            });
            return true;
        } else {
            // If the set frequency limit is exceeded , This time onDemandUpdate Method to submit the task 
            logger.warn("Ignoring onDemand update due to rate limiter");
            return false;
        }
    }

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • As shown in the above code , It can be seen that the functions mentioned in the previous notes have been implemented ;

  • thus ,InstanceInfoReplicator Analysis completed , It can be seen that this is a powerful auxiliary class , Check in on the application information Eureka server Has played an important role , The business logic can safely submit the submission request , Concurrent 、 Frequency overruns and other conditions are InstanceInfoReplicator It's handled ;

Welcome to your attention 51CTO Blog : Xinchen, programmer

  On the way to study , You are not alone , Xinchen's original works are accompanied all the way …

原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221232168780.html