“This is the second day of my participation in the November Gwen Challenge. See details of the event: The last Gwen Challenge 2021”.

The first public account of this article: Wukong chat framework link: click here

Eureka source client registry

Last time we looked at the Eureka startup process, this time we will analyze how the client is registered.

Leadership let me study had source | the boot process

The main contents of this paper are as follows:

Eureka Client is the Client. It can be the Eureka Server itself or the service instance to be registered, such as order service and commodity service.

When the @enableEurekaclient annotation is mentioned later, the current Application is registered with the Eureka service as a Eureka client.

So how is Eureka Client registered?

We can look at the construction and registration process of the EurekaClient using the example class ExampleEurekaClient provided with the Eureka source code.

First from the main method method, only from the main method, can not see where the registered code, then we will study the underlying source code.

public static void main(String[] args) throws UnknownHostException {
​
    injectEurekaConfiguration();
​
    ExampleEurekaClient sampleClient = new ExampleEurekaClient();
​
    // create the client
    ApplicationInfoManager applicationInfoManager = initializeApplicationInfoManager(new MyDataCenterInstanceConfig());
    EurekaClient client = initializeEurekaClient(applicationInfoManager, new DefaultEurekaClientConfig());
​
    // shutdown the client
    eurekaClient.shutdown();
}
Copy the code

Then let’s analyze what’s going on in Main step by step.

1. Initial configuration

1.1 Initializing variables

InjectEurekaConfiguration () method to initialize the Eureka some variables, such as port, the current service access path, whether you need to grab the registry information and so on.

private static void injectEurekaConfiguration() throws UnknownHostException {
    String myHostName = InetAddress.getLocalHost().getHostName();
    String myServiceUrl = "http://" + myHostName + ":8080/v2/";
​
    System.setProperty("eureka.region", "default");
    System.setProperty("eureka.name", "eureka");
    System.setProperty("eureka.vipAddress", "eureka.mydomain.net");
    System.setProperty("eureka.port", "8080");
    System.setProperty("eureka.preferSameZone", "false");
    System.setProperty("eureka.shouldUseDns", "false");
    System.setProperty("eureka.shouldFetchRegistry", "false");
    System.setProperty("eureka.serviceUrl.defaultZone", myServiceUrl);
    System.setProperty("eureka.serviceUrl.default.defaultZone", myServiceUrl);
    System.setProperty("eureka.awsAccessId", "fake_aws_access_id");
    System.setProperty("eureka.awsSecretKey", "fake_aws_secret_key");
    System.setProperty("eureka.numberRegistrySyncRetries", "0");
}
Copy the code

1.2 Obtaining the Configuration File

In this line of code, the configuration from the configuration file Eureka-client.properties is read and placed in EurekaInstanceConfig. This EurekaInstanceConfig is used to initialize the applicationInfoManager information manager.

Look at the following code creates a MyDataCenterInstanceConfig, is actually created EurekaInstanceConfig.

new MyDataCenterInstanceConfig()
Copy the code

What’s the relationship between the MyDataCenterInstanceConfig and EurekaInstanceConfig?

Can be seen in the relationship between the class diagram MyDataCenterInstanceConfig inheritance PropertiesInstanceConfig class, EurekaInstanceConfig interface is realized. This interface, which I’ve covered specifically, is used to get configuration information, similar to getXX().

A utility class is then called in the constructor of the PropertiesInstanceConfig class to read the values in the configuration file Eureka-client.properties. This is a little hidden!

Archaius1Utils.initConfig(CommonConstants.CONFIG_FILE_NAME);
Copy the code

1.3 Initial Instance Information

The main thing is to construct instanceInfo instance information. The information in this contains the configuration information in the initialization variable in the first step.

InstanceInfo instanceInfo = new EurekaConfigBasedInstanceInfoProvider(instanceConfig).get();
Copy the code

1.4 Initializing the Instance Information Manager

You hand instanceConfig and instanceInfo to the instance information manager.

applicationInfoManager = new ApplicationInfoManager(instanceConfig, instanceInfo);
Copy the code

2. Construct EurekaClient

2.1 Construction Process

The code that constructs eurekaClient

eurekaClient = new DiscoveryClient(applicationInfoManager, clientConfig);
Copy the code

DiscoveryClient is a subclass of EurekaClient. Building DiscoveryClient does the following:

  • Loading a Configuration File
  • Initialize the network transport component
  • The service instance configuration, configuration file configuration, and network transport components are assigned to DiscoveryClient.
  • Initialize two threads, one for heartbeat detection and one for cache flushing.
  • Initialize the network communication component EurekaTransport
  • Try to fetch the registry information. If not, fetch it from the alternate registry.
  • To initialize a scheduled scheduling task, perform the following operations: heartbeat check heartbeat, cacheRefresh cacheRefresh
  • In the initialization task initialization method, an InstanceInfoReplicator is initialized to register with eureka Server.
  • The initialization of the scheduled task method initializes a StatusChangeListener listener, which also has the registration logic.

Note: In the method of initializing the scheduling task, the above initialization operations are performed according to whether fetching registry information is enabled and whether eureka-client is registered with Eureka-server. The following code looks like this:

3. Eureka Client registration

3.1 Registration Process

The code that Eureka Client registers with the Server is hidden and hard to find. Instead of calling the registration method directly, it does so through a background thread, and the class that calls the registration method is also controversially named InstanceInfoReplicator. A “Replicator” means a copy, and the registration is not a copy, but sends the new registration information to the Eureka server, so the name of this class is not very good, and it is easy to find the registration code.

See how the Eureka client registers with the Eureka server.

(1) Registration is done through the InstanceInfoReplicator class. It is created when DiscoveryClient is constructed.

Started a thread that was delayed for 40 seconds,

instanceInfoReplicator.start(40); // Execute after 40 secondsCopy the code

(2) Then set a flag bit to true to indicate whether it has been registered.

instanceInfo.setIsDirty();
Copy the code

(3) Then call the registered method

discoveryClient.register();
Copy the code

The core code inside register() is

httpResponse = eurekaTransport.registrationClient.register(instanceInfo);
Copy the code

As you can imagine, this is an HTTP request that was sent when the Eureka client was registered.

EurekaTransport: Underlying transport component initialized when DiscoveryClient is initialized.

RegistrationClient: It is an abstract class that initializes the DiscoveryClient, by calling the scheduleServerEndpointTask () to initialize the specialized for registered registrationClient, Here is the SessionedEurekaHttpClient.

InstanceInfo: Is the current instance information to be sent to eureka Server for registration.

(4) Send post registration request

Perform the register () method, send the registration request is AbstractJerseyEurekaHttpClient class, this class in engineering had been – the client – jersey2 inside, use is the Jersey framework, domestic use of this framework is not much, Don’t go too far. The requested URL is

http://localhost:8080/v2/apps/EUREKA

The registered method sends a POST request. At this point, the Client registers with the Server.

response = resourceBuilder
    .accept(MediaType.APPLICATION_JSON)
    .acceptEncoding("gzip")
    .post(Entity.json(info));
Copy the code

So how does the Server save the registration information to its own registry? We’ll talk about that in the next chapter.

Four,

Eureka Client registers with Eureka Server:

(1) Eureka Client initializes a DiscoveryClient, captures the registry, and performs scheduling tasks.

(2) The InstanceInfoReplicator object starts a background thread with a delay of 40 s to execute the registration.

(3) and then use the AbstractJersey2EurekaHttpClient send a post request, the instanceInfo instance information sent to the Eureka Server.

The sequence diagram is as follows:

Leave a problem

When we use Eureka, Eureka discovers the existence of the Service immediately after it starts, as shown in the console interface below:

You don’t have to wait 40 seconds to sign up for Eureka, so why?

In the next article, we will look at how the Eureka Server saves the registration information sent by the Eureka Client.