Nocos name service

Provide the mapping management service between the “name” of all objects and entities in the distributed system and the associated metadata. For example, ServiceName -> Endpoints Info, Distributed Lock Name -> Lock Owner/Status Info, DNS Domain Name -> IP List, Service discovery and DNS are two scenarios of name services.

Client side

Start the service

com.alibaba.nacos.api.naming.NamingFactory

  1. createcom.alibaba.nacos.api.naming.NamingService
1.Factory created NamingService NamingFactory. CreateNamingService (properties)2.Creating a service implementationpublic static NamingService createNamingService(Properties properties) throws NacosException {
        try{ Class<? > driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingService");
            Constructor constructor = driverImplClass.getConstructor(Properties.class);
            NamingService vendorImpl = (NamingService) constructor.newInstance(properties);
            return vendorImpl;
        } catch (Throwable e) {
            throw newNacosException(NacosException.CLIENT_INVALID_PARAM, e); }}Copy the code

com.alibaba.nacos.client.naming.NacosNamingService

  1. Create NacosNamingService# # init ()
private void init(Properties properties) throws NacosException {
        // Check parameters
        ValidatorUtils.checkInitParam(properties);
        // Initialize the namespace through configuration
        this.namespace = InitUtils.initNamespaceForNaming(properties);
        InitUtils.initSerialization();
        initServerAddr(properties);
        InitUtils.initWebRootContext(properties);
        // Initialize the cache address
        initCacheDir();
        // Initialize the log name
        initLogName(properties);
        
        // Instance change notification
        this.changeNotifier = new InstancesChangeNotifier();
        NotifyCenter.registerToPublisher(InstancesChangeEvent.class, 16384);
        NotifyCenter.registerSubscriber(changeNotifier);
        
        this.serviceInfoHolder = new ServiceInfoHolder(namespace, properties);
        // Client proxy
        this.clientProxy = new NamingClientProxyDelegate(this.namespace,serviceInfoHolder, properties, changeNotifier);
}
Copy the code

Related Fields description

  • The namespace:

Used for configuration isolation of tenant granularity. Different namespaces can have the same Group or Data ID configuration. One of the common scenarios of Namespace is the isolation of configurations in different environments, such as the isolation of resources (such as configurations and services) between the development test environment and the production environment.

The service registry

NacosNamingService##registerInstance

    /**
     * register a instance to service with specified cluster name.
     *
     * @paramServiceName serviceName *@param ip          IP
     * @paramThe port port *@paramClusterName clusterName *@throws NacosException nacos exception
     */
    void registerInstance(String serviceName, String ip, int port, String clusterName) throws NacosException;
Copy the code

RegisterInstance method:

    @Override
    public void registerInstance(String serviceName, String groupName, String ip, int port, String clusterName)
            throws NacosException {
        // Assign to the instance object
        Instance instance = new Instance();
        instance.setIp(ip);
        instance.setPort(port);
        instance.setWeight(1.0);
        instance.setClusterName(clusterName);
        // Real registration service
        registerInstance(serviceName, groupName, instance);
    }
    
    @Override
    public void registerInstance(String serviceName, String groupName, Instance instance) throws NacosException {
        NamingUtils.checkInstanceIsLegal(instance);
        // The client proxy registers the service
        clientProxy.registerService(serviceName, groupName, instance);
    }
Copy the code

void registerService(String serviceName, String groupName, Instance instance)

When a service registers with the registry, the actual method is called:

    @Override
    public void registerService(String serviceName, String groupName, Instance instance) throws NacosException {
        
        // Check instance parameters
        NamingUtils.checkInstanceIsLegal(instance);
        // assemble name from serviceName and groupName in the format groupName @@servicename
        String groupedServiceName = NamingUtils.getGroupedName(serviceName, groupName);
        if (instance.isEphemeral()) {
            // Build the heartbeat information
            BeatInfo beatInfo = beatReactor.buildBeatInfo(groupedServiceName, instance);
            // Add heartbeat information to add a heartbeat detection task
            beatReactor.addBeatInfo(groupedServiceName, beatInfo);
        }
        
        final Map<String, String> params = new HashMap<String, String>(16);
        // omit arguments to build...
        
        reqApi(UtilAndComs.nacosUrlInstance, params, HttpMethod.POST);
        
    }
Copy the code

ServerProxy registerService registration link

  1. NameProxy# # reqApicallServerMethod to complete the service registration;
  2. The servers input parameter to the reqApi method is obtained via getServerList(), essentially from the serversFromEndpoint property
  3. ServersFromEndpoint initialization method in assignment getServerListFromEndpoint (), via Http requestshttp://" + endpoint + "/nacos/serverlistGets the service list.

extension

String# # intern () : tech.meituan.com/2014/03/06/…


Server part

The Nocos service API takes a restful approach, using the shareMethod method of the request to determine which implementation to use.

  1. Register service interface:POST /nacos/v1/ns/instance
    @CanDistro
    @PostMapping
    @Secured(parser = NamingResourceParser.class, action = ActionTypes.WRITE)
    public String register(HttpServletRequest request) throws Exception {
        /* * Omit the corresponding parameter value...... from request * /
        // Core method
        serviceManager.registerInstance(namespaceId, serviceName, instance);
        return "ok";
}
Copy the code
  1. Create a specific instance
    /** * Register an instance to a service in AP mode. * * <p>This method creates service or cluster silently if they don't  exist. * *@param namespaceId id of namespace
     * @param serviceName service name
     * @param instance    instance to register
     * @throws Exception any error occurred in the process
     */
    public void registerInstance(String namespaceId, String serviceName, Instance instance) throws NacosException {
        // Create an empty service, or if no service exists
        createEmptyService(namespaceId, serviceName, instance.isEphemeral());
          
        Service service = getService(namespaceId, serviceName);
        if (service == null) {
            throw new NacosException(NacosException.INVALID_PARAM,
                    "service not found, namespace: " + namespaceId + ", service: " + serviceName);
        }
        // Add an instance of the service
        addInstance(namespaceId, serviceName, instance.isEphemeral(), instance);
    }
Copy the code