“Understand in one article” Nacos service registration implementation principle

Contents of this chapter

Service Registry

The main function of the service registry is to store service registration information.

Service registry structure, as shown in the figure:

Service registry:

// com.alibaba.nacos.naming.core.ServiceManager#serviceMap
Map<String, Map<String, Service>> serviceMap = new ConcurrentHashMap<>();

in:

  • Outer map:
    • key: namespace (namespace), mainly used for environment isolation, such as: public, production environment, test environment, etc.
    • value: All service information under the namespace, which is a map structure.
  • Inner map:
    • key: group name@@service name, such as: DEFAULT_GROUP@@order-server, indicating service information under the grouping dimension.
    • value: service information, a Service instance.
  • Service Information:
    • key: service cluster name, such as DEFAULT.
    • value: service cluster information. A service cluster may contain multiple service instances, and each service instance will include two Set structures for storing temporary instances and persistent instances corresponding to the service.

Service instance:

// com.alibaba.nacos.naming.core.Service#clusterMap
private Map<String, Cluster> clusterMap = new HashMap<>();

Cluster instance:

// com.alibaba.nacos.naming.core.Cluster#persistentInstances
@JsonIgnore
private Set<Instance> persistentInstances = new HashSet<>();
// com.alibaba.nacos.naming.core.Cluster#ephemeralInstances
@JsonIgnore
private Set<Instance> ephemeralInstances = new HashSet<>();

Instance: Contains information such as InstanceId, IP, Port, health status, weight, etc.

Instance example:

  • instanceId: 192.168.31.106#8081#DEFAULT#DEFAULT_GROUP@@order-server.
  • IP: 192.168.31.106.
  • port:8081.
  • healthy: true.
  • weight: 1.0.
  • ephemeral: true.

Service registration process

When the service (Nacos client) starts, the service information is saved into the service registration table by calling the Nacos server service registration interface to complete the service registration.

Service registration interface

Request protocol: HTTP (gRPC is added in version 2.x)

Request type: POST

Request path:/nacos/v1/ns/instance

Request parameters

response encoding

Client

When the service (Nacos client) starts, the service registration process is started by listening to the service initialization completion event, and the service registration interface provided by the Nacos server is called to complete the service registration.

Service registration process

as the picture shows:

Processing steps:

  • 1) When the service is started, the initialization completion event is released after the Spring container initialization is completed. AbstractAutoServiceRegistration implements the onApplicationEvent() method of the ApplicationListener interface. Therefore, the AbstractAutoServiceRegistration.onApplicationEvent() method will be triggered, and the bind() method is called in this method to start service registration. process.
  • 2) Create a service instance to encapsulate service registration information.
  • 3) If the instance type is a temporary instance, send heartbeat requests to the Nacos server regularly (5 seconds/time).
  • 4) Assemble the request parameters and call the service registration interface to register the service instance with the Nacos server.

Server

After receiving the client registration request, the Nacos server registers the service into the service registry through the processing method corresponding to the service registration interface.

The Nacos server startup class is the com.alibaba.nacos.Nacos class in the nacos-console module, and the nacos-naming module is introduced in the nacos-console module. The controllers package of the nacos-naming module includes service registration, service discovery, There are many types of control processors such as service renewal, among which the control processor corresponding to service registration is: InstanceController.

Service registration process

as the picture shows:

In the picture:

  • The red part indicates getting the latest instance list of the service.
  • The yellow part indicates updating the latest instance information of the service into the registry (ie: service registration).
  • The blue part indicates that the service information is synchronized to other Nacos nodes in the cluster through the Distro protocol.

Processing steps:

  • 1) The Nacos server receives the client registration request, obtains the namespace ID and service name based on the request parameters, and generates the corresponding service instance.
  • 2) Create and initialize the Service and add it to the registry (for the first time registering the service).
  • 3) Obtain the corresponding service information from the registry according to namespaceId, serviceName.
  • 4) Generate a service unique identifier based on namespaceId, serviceName, and instance type (temporary, persistent).
  • 5) Get the latest instance list (old instance list + to-be-registered instance list).
  • 6) Determine the service instance type (temporary, persistent) based on the unique service identifier prefix and select different protocols for service registration and synchronization (taking temporary instances as an example).
  • 7) Service registration:
    • Encapsulate the instance list information corresponding to the service into Datum and add it to the DataStore (data set).
    • Encapsulate the service’s unique identifier and operation type into a Task and add it to the task queue of DistroConsistencyServiceImpl.Notifier.
    • The asynchronous thread Notifier in the thread pool takes out tasks from the task queue for processing in an infinite loop:
      • Update operation:
        • Update the instance list information corresponding to the service (ie: replace the old instance + add a new instance).
        • Update service MD5 check code.
      • Delete operation:
        • Update the instance list information corresponding to the service (that is, remove the instance from the service instance list).
  • 8) Service information synchronization (traverse other Nacos nodes in the cluster except itself):
    • Encapsulate service information, resource type and target node into DistroKey.
    • Encapsulate the DistroKey and operation type into a delayed task DelayTask and add it to the task collection of the Nacos delayed task executor.
    • The scheduled task takes out tasks from the task collection through the asynchronous processing thread ProcessRunnable in the thread pool for data synchronization processing.
    • If the task processing fails, the task will be re-added to the task collection and retried.

Service registration FAQ

1) How does the Nacos server support high concurrent registration?

Use queue + asynchronous thread method for service registration to prevent the client from writing registration information to the registry synchronously.

2) How does the Nacos server ensure concurrency security?

When registering a service instance with the registration center, a synchronization lock will be added to the Service object to ensure the security of concurrent writing of service instance information.

3) How does the Nacos server avoid concurrent read and write conflicts?

Using the idea of CopyOnWrite, when updating (adding, modifying, deleting, etc.) service information, first copy the existing service information, generate a copy of the service information, update the service information in the copy of the service information, and directly replace the existing service information after the update is completed. Complete Service information updated.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 139386 people are learning the system