The main purpose of this article is to explain the process, so in addition to the method name is the source code, other code is abbreviated or rewritten, can be seen as pseudocode, just to express logic and show the process.

The content of a method call in one code block can basically be found in this code block or the next code block.

The service registry

The Nacos server is a Web project, and all you do with Nacos is send an HTTP request, so you just need to find out where Spring-cloud-Alibaba-Nacos sent the request.

  1. When Spring Boot starts, Spring’s Refresh method is called to complete the boot of Spring, and at the end of the boot, the finishRefresh method is called. The ultimate purpose of this method is to call the start method of all the SmartLifecycle implementation classes in the Spring container

    @Override public void refresh() throws BeansException, IllegalStateException { //... finishRefresh(); / /... }
    protected void finishRefresh() { //... / / initializes the life cycle of the processor, the default for DefaultLifecycleProcessor initLifecycleProcessor (); // Call the lifecycle processor onRefresh GetLifecyCleProcessor ().onRefresh(); / /... }
    public class DefaultLifecycleProcessor{ @Override public void onRefresh() { startBeans(true); } private void StartBeans (Boolean AutoStartupOnly) {// Get the bean SmartLifecycle that is the implementation class of SmartLifecycle in the Spring container beans=getSmartLifecycleBeans(); Phased for(SmartLifecycle: Beans){//SmartLifecycle implemented a Phased interface that returns an int value indicating the order in which the number is smaller and the int phase= Bean.getPhase () is called first; // Put the bean into the lifecycleGroup, LifecycleGroup =new LifecycleGroup(phase,bean); LifecycleGroup =new LifecycleGroup(phase,bean); } // Sort (lifecycleGroups) by phase value; // Call lifecycleGroup's start lifecyclegroups.start () sequentially; } private class LifecycleGroup {public void start() {doStart(bean); } private void doStart(){ bean.start() } } }
  2. Spring boot offers a SmartLifecycle implementation class WebServerStartStopLifecycle, and rewrite the start method

    / / this is under the servlet package, reactive under reactive package, is also a publish event package org. Springframework. Boot. Web. Servlet. The context; Public void start() {// Publishes an event in the start method, Said the Servlet initialization web server has completed applicationContext. PublishEvent (new ServletWebServerInitializedEvent ()); }
    / / this event inheritance of public class ServletWebServerInitializedEvent extends WebServerInitializedEvent
  3. Spring – cloud provides an abstract class monitor WebServerInitializedEvent events

    public abstract class AbstractAutoServiceRegistration<R extends Registration> implements ApplicationListener < WebServerInitializedEvent > {/ / use the decorator pattern here, Need to incoming data from the subclass protected AbstractAutoServiceRegistration (ServiceRegistry < R > ServiceRegistry. AutoServiceRegistrationProperties properties) { this.serviceRegistry = serviceRegistry; this.properties = properties; } public void onApplicationEvent(WebServerInitializedEvent event) { this.bind(event); } public void bind(WebServerInitializedEvent event) { this.start(); } public void start() {this.register();} public void start() {this.register(); this.register(); } // call the top button, call it here, Protected void register() {// Get Registration from a subclass and use the ServiceRegistry passed in by the subclass to register this.serviceRegistry.register(this.getRegistration()); } protected abstract R getRegistration(); }

    Take a quick look at the Registration and ServiceRegistry interfaces

    1. public interface ServiceInstance { String getServiceId(); String getHost(); int getPort(); Public interface Registration extends ServiceInstance {} public interface Registration extends ServiceInstance {}
    2. Register = register = register = register = register Public Interface ServiceRegistry<R extends Registration> {void register(R Registration); }
  4. Spring – the cloud – alibaba – nacos provides AbstractAutoServiceRegistration implementation class, from the point of inheritance, is essentially a listening WebServerInitializedEvent listener

    Public class NacosAutoServiceRegistration extends AbstractAutoServiceRegistration < Registration > {/ / incoming registry and Registration required basic information to the public  NacosAutoServiceRegistration(ServiceRegistry<Registration> serviceRegistry, AutoServiceRegistrationProperties properties, NacosRegistration registration) {/ / the serviceRegistry incoming parent super (serviceRegistry autoServiceRegistrationProperties); this.registration = registration; } @override // return registration protected NacosRegistration getRegistration() {return this.registration; }}

    NacosAutoServiceRegistration object is created in the automatic configuration class of general logic springboot automatic configuration

    SpringBoot will fetch the key and value pairs in the classpath*:META-INF/spring.factories when it starts

    Spring’s general parsing logic is then used to parse the class represented by Value. This is done by: org.springframework.context.annotation.ConfigurationClassParser#doProcessConfigurationClass

    #spring-cloud-starter-alibaba-nacos- Factories in the sping-cloud-starter-alibaba-nacos -discovery package This is only one value org. Springframework. Boot. Autoconfigure. EnableAutoConfiguration = \ com.alibaba.cloud.nacos.registry.NacosServiceRegistryAutoConfiguration
    public class NacosServiceRegistryAutoConfiguration { @Bean public NacosServiceRegistry nacosServiceRegistry() { return new NacosServiceRegistry(); } @Bean public NacosRegistration nacosRegistration() { return new NacosRegistration(); } @Bean public NacosAutoServiceRegistration nacosAutoServiceRegistration( NacosServiceRegistry registry, NacosRegistration registration) { return new NacosAutoServiceRegistration(registry, registration); }}
  5. NACOS registration logic

    public class NacosServiceRegistry implements ServiceRegistry<Registration>{ @Override public void register(Registration Registration) {// This NamingService is a class in the Nacos-API package that was created during the creation of the HealthIndicator // in the autoconfig class. NacosNamingService namingService = namingService(); NacosNamingService = namingService(); Instance Instance = createEnacosInstance (registration); / / registration service namingService. RegisterInstance (serviceId, group, the instance); }
    public class NacosNamingService implements NamingService{ @Override public void registerInstance(String serviceName, String groupName, The Instance Instance) throws NacosException {/ / heartbeat information BeatInfo BeatInfo = beatReactor. BuildBeatInfo (groupedServiceName, instance); // Send heartbeat information, that is, send a request to the Nacos server every once in a while, Beatreactor. addBeatInfo(groupedServiceName, beatInfo); beatInfo (groupedServiceName, beatInfo); / / send the registration request / / serverProxy serverProxy the constructor is created. The registerService (groupedServiceName, groupName, instance); }}
    Public class beatInfo (String ServiceName, beatInfo) {public void addBeatInfo(String ServiceName, beatInfo) {public void addBeatInfo(String ServiceName, beatInfo) { // Runtime.getRuntime().availableProcessors().availableProcessors().availableProcessors(); // The first parameter is the task to execute, the second is the delay time (default 5 seconds), and the third is the TimeUnit executorService.schedule(new beatTask (beatInfo), beatInfo.getPeriod(), timeUnit); }} class beatTask implements Runnable {@Override public void run() {// Send the heartbeat to ServerProxy.sendBeat (beatInfo); ExecutorService.schedule (new beatTask (beatInfo), beatInfo.getPeriod(), TimeUnit); // ExecutorService.schedule (beatInfo); }}

    This is an instance of the registration request provided on the NACOS website, so you just need to build the request and send it to the NACOS server

    The curl -x POST ‘http://127.0.0.1:8848/nacos/v…

    Public void RegisterService (String ServiceName, String GroupName) {public void RegisterService (String ServiceName, String GroupName) {public void RegisterService (String ServiceName, String GroupName); Throws NacosException {// Instance throws NacosException { // Use the three parameters passed in to build the params // build the header // build the URI // Use the NacosRestTemplate to send the request, Using JdkHttpClientRequest inside, / / to use inside the sun.net.www.protocol.http.HttpURLConnection / / request to nacos server arise, finished. // There is a return value in the HTTP request, and Nacos also creates a responseHandler to parse the return value as an HttpRestResult, but the return value is not used in the process. // The heartbeat is also sent as an HTTP request, so the logic is similar to that of registration. reqApi(UtilAndComs.nacosUrlInstance, params, HttpMethod.POST); }}

conclusion

I. Spring, the start method of SmartLifecycle is called upon completion of the launch

2. Spring – the boot, provides SmartLifecycle implementation class WebServerStartStopLifecycle, released ServletWebServerInitializedEvent in the start

3. Spring – cloud, using an abstract class AbstractAutoServiceRegistration listening ServletWebServerInitializedEvent, Register the service by calling ServiceRegistry and Registration of subclasses

4. Spring – the cloud – alibaba – nacos, provides AbstractAutoServiceRegistration implementation class NacosServiceRegistryAutoConfiguration, and initialized in the automatic configuration class.

In NacosServiceRegistryAutoConfiguration nacos, completed the construction of a specific HTTP request and send