In the previous article, we introduced the function and design architecture of Nacos. This article focuses on the service registration function provided by Nacos to explain how the client of Nacos is integrated and implemented in Spring Cloud.

This association with source code analysis, flow chart sorting, core API analysis and other dimensions to let everyone in simple, systematic learning.

Automatic registration for Spring Boot

The story starts with automatic injection from Spring Boot. Many of you are probably familiar with Spring Boot’s automatic configuration, and Spring Cloud is based on the Spring Boot framework.

Therefore, before learning about the Nacos registration business, let’s review the automatic configuration principle of Spring Boot as an entry point for learning.

SpringBoot uses the @enableAutoConfiguration annotation to load all eligible @Configuration configurations into the IoC container that SpringBoot is currently creating and using.

This process is through @ Import (AutoConfigurationImportSelector. Class) Import configuration function, Method of AutoConfigurationImportSelector getCandidateConfigurations, get set to configure the class name of the class, namely all needs to carry on the automatic configuration (xxxAutoConfiguration) class, These classes are configured in the meta-INF /spring.factories file.

Finally, based on the fully qualified name annotation on the class, such as: OnClassCondition, OnBeanCondition, OnWebApplicationCondition condition of deciding to automatic configuration.

Now that you know the basic configuration of Spring Boot, let’s take a look at where the Nacos auto-configuration is.

Nacos is automatically configured in Spring Cloud

Check the project dependencies of Spring Cloud. The jar package corresponding to the dependencies I introduced is Spring-cloud-starter-Alibaba-nacos-discovery-2021.1.jar.

The corresponding POM dependency is:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
Copy the code

The meta-INF /spring.factories file is in the jar.

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration,\
  com.alibaba.cloud.nacos.endpoint.NacosDiscoveryEndpointAutoConfiguration,\
  com.alibaba.cloud.nacos.registry.NacosServiceRegistryAutoConfiguration,\
  com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration,\
  com.alibaba.cloud.nacos.discovery.reactive.NacosReactiveDiscoveryClientConfiguration,\
  com.alibaba.cloud.nacos.discovery.configclient.NacosConfigServerAutoConfiguration,\
  com.alibaba.cloud.nacos.NacosServiceAutoConfiguration
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
  com.alibaba.cloud.nacos.discovery.configclient.NacosDiscoveryClientConfigServiceBootstrapConfiguration
Copy the code

You can see that the EnableAutoConfiguration class corresponds to a series of Nacos auto-configuration classes.

The NacosServiceRegistryAutoConfiguration is used to encapsulate instantiation Nacos registration process required components, Loaded with three objects NacosServiceRegistry, NacosRegistration, NacosAutoServiceRegistration, the three object as a whole is used for Nacos service registration.

@Configuration(proxyBeanMethods = false) @EnableConfigurationProperties @ConditionalOnNacosDiscoveryEnabled @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) @AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class, AutoServiceRegistrationAutoConfiguration.class, NacosDiscoveryAutoConfiguration.class }) public class NacosServiceRegistryAutoConfiguration { @Bean public NacosServiceRegistry nacosServiceRegistry( NacosDiscoveryProperties nacosDiscoveryProperties) { return new NacosServiceRegistry(nacosDiscoveryProperties); } @Bean @ConditionalOnBean(AutoServiceRegistrationProperties.class) public NacosRegistration nacosRegistration( ObjectProvider<List<NacosRegistrationCustomizer>> registrationCustomizers, NacosDiscoveryProperties nacosDiscoveryProperties, ApplicationContext context) { return new NacosRegistration(registrationCustomizers.getIfAvailable(), nacosDiscoveryProperties, context); } @Bean @ConditionalOnBean(AutoServiceRegistrationProperties.class) public NacosAutoServiceRegistration nacosAutoServiceRegistration( NacosServiceRegistry registry, AutoServiceRegistrationProperties autoServiceRegistrationProperties, NacosRegistration registration) { return new NacosAutoServiceRegistration(registry, autoServiceRegistrationProperties, registration); }}Copy the code

NacosServiceRegistry encapsulates the registration process, which inherits from ServiceRegistry:

public class NacosServiceRegistry implements ServiceRegistry<Registration> {... }Copy the code

View the source code of this class, you can see that this class has realized the service registration, logout, close, set the state, obtain the state of five functions.

The service registration function we are tracking is implemented through the register method it provides.

At this point, we can walk through the process of integrating and instantiating the Nacos client in the Spring Cloud.

Spring Cloud’s ServiceRegistry interface

NacosServiceRegistry integrates with ServiceRegistry, so what is ServiceRegistry?

The ServiceRegistry interface is a Spring Cloud class.

public interface ServiceRegistry<R extends Registration> {

	void register(R registration);
	void deregister(R registration);
	void close();
	void setStatus(R registration, String status);
	<T> T getStatus(R registration);
}
Copy the code

You can see that the ServiceRegistry interface defines five interfaces for registering, deregistry, closing, setting state, and getting state.

If you look at other service discovery frameworks integrating with Spring Cloud, they basically implement this interface. In other words, ServiceRegistry is a specification for service discovery framework integration provided by Spring Cloud. The corresponding framework installation specifications can be integrated to achieve the corresponding functions.

We can see that Eureka, Zookeeper, and Consul all implement this interface in Spring Cloud integration, and if you need to customize service discovery capabilities, you can also implement this interface.

NacosServiceRegistry service implementation

Ignoring the other helper classes, let’s go straight to the NacosServiceRegistry# Register method, which provides the core business logic implementation for service registration.

We remove the auxiliary judgment of this class and show the core code as follows:

@override public void register(Registration) {// Obtain NamingService NamingService = namingService(); String serviceId = registration.getServiceId(); String group = nacosDiscoveryProperties.getGroup(); / / structure as an example, encapsulate the information is from the configuration properties Instance Instance = getNacosInstanceFromRegistration (registration); / / the instance to register namingService. RegisterInstance (serviceId, group, the instance); }Copy the code

NamingService in the above code is already supported by the API provided by the Nacos Client project.

About the API process of Nacos Client, you can directly view the corresponding source code of Nacos, NamingService#registerInstance method corresponding flow chart is compiled as follows:

The above flow chart can be further refined, which will be specially explained in the following chapters. Here you can know the general call process.

Spring Cloud service registers links

Let’s take a look at how Spring Cloud registers services. The first two thirds of the process are almost all of the service registration frameworks are the same process, and only the last part is implemented by invoking specific frameworks when instances are registered.

To look directly at the link diagram of the entire call:

The different colors in the figure represent the different frameworks. Gray represents the business code, light green represents the SpringBoot framework, dark green represents the Spring framework, and light orange represents the SpringCloud framework. This part also contains the Nacos component parts that depend on it. The last light purple represents the Nacos Client package.

The core process is divided into the following steps:

In the first step, SpringBoot calls refresh, Spring’s core method, when starting the main method.

The second step is to instantiate the WebServerStartStopLifecycle object in the Spring.

Key said the WebServerStartStopLifecycle object, its start method is called when released a ServletWebServerInitializedEvent event class, This event class inherits from WebServerInitializedEvent. Back to deal with registered service class AbstractAutoServiceRegistration is also a listener, designed to monitor WebServerInitializedEvent events.

In the third step, AbstractApplicationContext finishRefresh indirect call DefaultLifecycleProcessor startBeans method, Then call the WebServerStartStopLifecycle start method. As stated above, triggered release ServletWebServerInitializedEvent events.

The fourth step, AbstractAutoServiceRegistration listening to the corresponding event, and then based on the Spring Cloud ServiceRegistry interfaces defined in the service registry.

The above description leaves out some of the details, but the whole process is basically SpringBoot publishing an event at startup, Spring Cloud listening for the event, and then registering the service.

summary

For this article, liver several days. Spring Cloud source code, Spring Boot source code, Nacos source code have turned over. Finally, we share the implementation mechanism and process of service discovery in Nacos or Spring Cloud.

The reason for writing this article is to advocate more into the source code, rather than just in use. Did you learn?

PS: I plan to study the source code of the Spring Cloud microservices family for a long period of time, and dig into the underlying source code like this article. Nacos (Service discovery) is only open, if you are interested in this aspect, add wechat friends, note Nacos, when enough people will set up related communication groups.

Nacos series

  • Want to learn the service discovery of micro-service? Let’s learn some popular science knowledge first.

  • Nacos, the Soul Ferryman of Microservices, here is a complete overview of the principle.

  • You are also interested in reading the source code. Tell me how I read the source code of Nacos

  • Nacos already has Optional use cases, so it’s time to take this syntax seriously.

  • Why is the String. Intern method used in Nacos source code?


Program new horizon

\

The public account “program new vision”, a platform for simultaneous improvement of soft power and hard technology, provides massive information

\