The foreword 0.

  • Springboot version: 2.1.9.RELEASE
  • Springcloud version: Greenwich.SR4

1. Register the service instance

When the client triggers registration:

  • Initiate registration when the client starts, when the profile is configuredeureka.client.should-enforce-registration-at-init = trueIf no, the default value is false
  • When the client periodically sends heartbeat lease renewal requests to the server, the server returns 404, and the client initiates registration immediately
  • The client periodically checks its own data status and initiates registration when related information (data center, instance information, and health status) changes

2. register()

In all of the cases that trigger registration, the register() method in the DiscoveryClient class is called

// DiscoveryClient.class
boolean register(a) throws Throwable {
    logger.info(PREFIX + "{}: registering service...", appPathIdentifier);
    EurekaHttpResponse<Void> httpResponse;
    try {
        // 2.1 Initiate Jersey registration request
        httpResponse = eurekaTransport.registrationClient.register(instanceInfo);
    } catch (Exception e) {
        logger.warn(PREFIX + "{} - registration failed {}", appPathIdentifier, e.getMessage(), e);
        throw e;
    }
    if (logger.isInfoEnabled()) {
        logger.info(PREFIX + "{} - registration status: {}", appPathIdentifier, httpResponse.getStatusCode());
    }
    // The server returns 204, indicating that the registration is successful but no data is returned
    return httpResponse.getStatusCode() == Status.NO_CONTENT.getStatusCode();
}
Copy the code

2.1 Initiate Jersey registration request

Jersey is a REST framework that provides JAX-RS reference implementations, among other things. Jersey provides its own apis that extend the JAX-RS toolkit and have other features and utilities to further simplify RESTful service and client development. Jersey also exposes a number of extension SPIs for developers to extend based on their own needs.

// AbstractJerseyEurekaHttpClient.class
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);
        // Submit the POST request through Jersey
        response = resourceBuilder
                .header("Accept-Encoding"."gzip")
                .type(MediaType.APPLICATION_JSON_TYPE)
                .accept(MediaType.APPLICATION_JSON)
                .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(); }}}Copy the code

3. The service instance is removed

// DiscoveryClient.class
public synchronized void shutdown(a) {
    if (isShutdown.compareAndSet(false.true)) {
        logger.info("Shutting down DiscoveryClient ...");

        if(statusChangeListener ! =null&& applicationInfoManager ! =null) {
            // Unregister the status change listener
            applicationInfoManager.unregisterStatusChangeListener(statusChangeListener.getId());
        }

        // Stop the scheduled task and then stop the task executor
        cancelScheduledTasks();

        // If APPINFO was registered
        if(applicationInfoManager ! =null
                && clientConfig.shouldRegisterWithEureka()
                && clientConfig.shouldUnregisterOnShutdown()) {
            applicationInfoManager.setInstanceStatus(InstanceStatus.DOWN);
            // 3.1 Deregister the current service instance to the server and initiate the removal
            unregister();
        }

        if(eurekaTransport ! =null) {
            
            eurekaTransport.shutdown();
        }

        // Deregister related monitoring
        heartbeatStalenessMonitor.shutdown();
        registryStalenessMonitor.shutdown();

        logger.info("Completed shut down of DiscoveryClient"); }}Copy the code

3.1 Deregistering the Current Service Instance from the Server

// DiscoveryClient.class
void unregister(a) {
    // It can be null if shouldRegisterWithEureka == false
    if(eurekaTransport ! =null&& eurekaTransport.registrationClient ! =null) {
        try {
            logger.info("Unregistering ...");
            // Initiate Jersey takedown request, similar to the registration above
            EurekaHttpResponse<Void> httpResponse = eurekaTransport.registrationClient.cancel(instanceInfo.getAppName(), instanceInfo.getId());
            logger.info(PREFIX + "{} - deregister status: {}", appPathIdentifier, httpResponse.getStatusCode());
        } catch (Exception e) {
            logger.error(PREFIX + "{} - de-registration failed{}", appPathIdentifier, e.getMessage(), e); }}}Copy the code