Six, eureka client automatically registered service

All articles

https://www.cnblogs.com/lay2017/p/11908715.html

 

text

Last article , we understand a little bit how eureka client is automatically configured, what things are configured. When automatic configuration will produce a charge of automatic registration of Bean, that is,

@Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
@ConditionalOnProperty(
        value = "spring.cloud.service-registry.auto-registration.enabled",
        matchIfMissing = true)
public EurekaAutoServiceRegistration eurekaAutoServiceRegistration(
        ApplicationContext context, EurekaServiceRegistry registry,
        EurekaRegistration registration) {
    return new EurekaAutoServiceRegistration(context, registry, registration);
}

 

So, we look at open EurekaAutoServiceRegistration

public class EurekaAutoServiceRegistration implements AutoServiceRegistration, SmartLifecycle, Ordered, SmartApplicationListener {

    private ApplicationContext context;

    private EurekaServiceRegistry serviceRegistry;

    private EurekaRegistration registration;

    public EurekaAutoServiceRegistration(ApplicationContext context, EurekaServiceRegistry serviceRegistry, EurekaRegistration registration) {
        this.context = context;
        this.serviceRegistry = serviceRegistry;
        this.registration = registration;
    }

    @Override
    public void start() {
        // ...

        if (!this.running.get() && this.registration.getNonSecurePort() > 0) {

            // 调用注册
            this.serviceRegistry.register(this.registration);

            this.context.publishEvent(new InstanceRegisteredEvent<>(this, this.registration.getInstanceConfig()));

            this.running.set(true);
        }
    }

}

 

Sign tasks are delegated to the serviceRegistry to do to follow up on the register method

@Override
public void register(EurekaRegistration reg) {
    maybeInitializeClient(reg);

    // ...

    reg.getApplicationInfoManager().setInstanceStatus(reg.getInstanceConfig().getInitialStatus());

    reg.getHealthCheckHandler().ifAvailable(healthCheckHandler -> reg.getEurekaClient().registerHealthCheck(healthCheckHandler));
}

Call eurekaClient original registerhealthCheck method, follow it

@Override
public void registerHealthCheck(HealthCheckHandler healthCheckHandler) {
    if (instanceInfo == null) {
        logger.error("Cannot register a healthcheck handler when instance info is null!");
    }
    if (healthCheckHandler != null) {
        // 注册心跳检查处理器
        this.healthCheckHandlerRef.set(healthCheckHandler);
        
        // schedule an onDemand update of the instanceInfo when a new healthcheck handler is registered
        if (instanceInfoReplicator != null) {
            instanceInfoReplicator.onDemandUpdate();
        }
    }
}

The processor is arranged to check the heart rate variable member, the core logic execution is entrusted to onDemandUpdate methods, which follow

public boolean onDemandUpdate() {
    if (rateLimiter.acquire(burstSize, allowedRatePerMinute)) {
        if (!scheduler.isShutdown()) {
            scheduler.submit(new Runnable() {
                @Override
                public void run() {
                    // ...

                    InstanceInfoReplicator.this.run();
                }
            });
            return true;
        } else {
            // ... 
        }
    } else {
        // ...
    }
}

Single-threaded asynchronous execution of the run method of the current class into the run method

public  void RUN () {
     the try {
         // refresh instance information 
        discoveryClient.refreshInstanceInfo ();
 
        Long dirtyTimestamp = instanceInfo.isDirtyWithTime ();
         IF (! dirtyTimestamp = null ) {
             // Register 
            discoveryClient.register (); 
            instanceInfo.unsetIsDirty (dirtyTimestamp ); 
        } 
    } the catch (the Throwable T) {
         // ... 
    } the finally {
         // next time delays execution 
        Future next = scheduler.schedule (this, replicationIntervalSeconds, TimeUnit.SECONDS);
        scheduledPeriodicRef.set(next);
    }
}

run method every time the refresh instance information, call register and then register a new instance of information, and then sent the next time delay task execution

 

Follow register method

boolean register() throws Throwable {
    logger.info(PREFIX + "{}: registering service...", appPathIdentifier);
    EurekaHttpResponse<Void> httpResponse;
    try {
        // 发出远程请求
        httpResponse = eurekaTransport.registrationClient.register(instanceInfo);
    } catch (Exception e) {
        
    }
    
    return httpResponse.getStatusCode() == Status.NO_CONTENT.getStatusCode();
}

Continue to follow up the register method, issued a http request as an example here to jersey

@Override
public EurekaHttpResponse<Void> register(InstanceInfo info) {
    String urlPath = "apps/" + info.getAppName();
    ClientResponse response = null;
    try {
        Builder resourceBuilder = jerseyClient.resource(serviceUrl).path(urlPath).getRequestBuilder();
        addExtraHeaders(resourceBuilder);
        response = resourceBuilder
                .header("Accept-Encoding", "gzip")
                .type(MediaType.APPLICATION_JSON_TYPE)
                .accept(MediaType.APPLICATION_JSON)
                // 发出http请求
                .post(ClientResponse.class, info);
        return anEurekaHttpResponse(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();
        }
    }
}

http request will enter eureka server, registration information examples are interested can look eureka server registered service this.

 

to sum up

eureka client automatically registered when the service is mainly configured automatically get the instance information sent via http request to the server eureka, default 30 seconds will be executed once.

 

 

 

 

Guess you like

Origin www.cnblogs.com/lay2017/p/11922673.html