Cloud Native 17 min read

Mastering Nacos Service Discovery: Models, APIs, and Best Practices

This article explains Nacos's service discovery model, including its multi‑layer namespace‑group‑service‑cluster‑instance structure, practical code examples for registering services and instances, customization options, isolation strategies, and both pull and push discovery mechanisms for robust microservice architectures.

Alibaba Cloud Developer
Alibaba Cloud Developer
Alibaba Cloud Developer
Mastering Nacos Service Discovery: Models, APIs, and Best Practices

Introduction

According to current market scenarios, Nacos provides two main functions: service registration & discovery (Naming) and configuration center (Config). This article focuses on the service registration and discovery side, discussing Nacos's service model from a user perspective.

Service Model Overview

Nacos adopts a multi‑layer domain model consisting of Namespace → Group → Service → Cluster → Instance. Service and Instance are core, while Namespace, Group, and Cluster provide isolation at different granularities.

Compared with Zookeeper, which lacks a built‑in service model, Nacos defines its own model to simplify integration with microservice frameworks such as Dubbo and Spring Cloud.

Mapping to Dubbo and Spring Cloud

Dubbo maps the triple interface name + group + version to a Service and registers IP + port as an Instance. Example registration string: providers:com.alibaba.mse.EchoService:1.0.0:DUBBO Spring Cloud maps the application name to a Service and registers IP + port as an Instance. Example service name:

helloApp

Environment Preparation

Deploy a Nacos server for testing, either by purchasing an Alibaba Cloud MSE hosted Nacos instance or by setting up a self‑hosted server.

Quick Start Demo

Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.SERVER_ADDR, "mse-xxxx-p.nacos-ans.mse.aliyuncs.com:8848");

String serviceName = "nacos.test.service.1";
String instanceIp = InetAddress.getLocalHost().getHostAddress();
int instancePort = 8080;

namingService.registerInstance(serviceName, instanceIp, instancePort);

System.out.println(namingService.getAllInstances(serviceName));

This code registers a simple service named nacos.test.service.1 with a single instance using the local host IP and port 8080.

Custom Instance Registration

To customize instance attributes such as weight, health status, or metadata, use the overloaded registerInstance method that accepts an Instance object.

/**
 * register a instance to service with specified instance properties.
 *
 * @param serviceName name of service
 * @param groupName   group of service
 * @param instance    instance to register
 * @throws NacosException nacos exception
 */
void registerInstance(String serviceName, String groupName, Instance instance) throws NacosException;
public class Instance {
    /** unique id of this instance. */
    private String instanceId;
    /** instance ip. */
    private String ip;
    /** instance port. */
    private int port;
    /** instance weight. */
    private double weight = 1.0D;
    /** instance health status. */
    private boolean healthy = true;
    /** If instance is enabled to accept request. */
    private boolean enabled = true;
    /** If instance is ephemeral. */
    private boolean ephemeral = true;
    /** cluster information of instance. */
    private String clusterName;
    /** Service information of instance. */
    private String serviceName;
    /** user extended attributes. */
    private Map<String, String> metadata = new HashMap<String, String>();
}

Key fields include healthy, enabled, ephemeral, and metadata for custom tags such as data‑center or weight.

Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.SERVER_ADDR, "mse-xxxx-p.nacos-ans.mse.aliyuncs.com:8848");
properties.setProperty(PropertyKeyConst.NAMESPACE, "9125571e-bf50-4260-9be5-18a3b2e3605b");

NamingService namingService = NacosFactory.createNamingService(properties);
String serviceName = "nacos.test.service.1";
String group = "DEFAULT_GROUP";
String clusterName = "cn-hangzhou";
String instanceIp = InetAddress.getLocalHost().getHostAddress();
int instancePort = 8080;
Instance instance = new Instance();
instance.setClusterName(clusterName);
instance.setIp(instanceIp);
instance.setPort(instancePort);
Map<String, String> metadata = new HashMap<>();
metadata.put("app", "nacos-demo");
metadata.put("site", "cn-hangzhou");
metadata.put("protocol", "1.3.3");
instance.setMetadata(metadata);

namingService.registerInstance(serviceName, group, instance);

System.out.println(namingService.getAllInstances(serviceName));

Images below show the registration results in the console and the MSE Nacos visual console.

Custom Service Configuration

While Nacos allows custom service attributes via OpenAPI, most users configure services indirectly through instance registration. The service data structure is:

/** Service name */
private String name;
private float protectThreshold = 0.0F;
private String app;
private String group;
private String healthCheckMode;
private Map<String, String> metadata = new HashMap<String, String>();

Isolation Strategies: Namespace, Group, Cluster

Cluster : Used internally at Alibaba for health‑check variations or environment‑based traffic splitting.

Group : Similar to Dubbo's grouping; default is DEFAULT_GROUP.

Namespace : Commonly used to isolate environments such as dev, test, uat, prod; recommended for non‑production isolation.

Service Discovery: Pull and Push Models

Nacos provides three synchronous pull APIs:

/** Get all instances of a service */
List<Instance> getAllInstances(String serviceName) throws NacosException;
/** Get qualified instances (healthy flag) */
List<Instance> selectInstances(String serviceName, boolean healthy) throws NacosException;
/** Select one healthy instance using load‑balance */
Instance selectOneHealthyInstance(String serviceName) throws NacosException;

For event‑driven discovery, Nacos offers subscription APIs:

/** Subscribe service to receive instance changes */
void subscribe(String serviceName, EventListener listener) throws NacosException;
/** Unsubscribe */
void unsubscribe(String serviceName, EventListener listener) throws NacosException;

Consumers typically fetch the full instance list once at startup, then subscribe to receive real‑time updates.

Conclusion

Nacos implements a mature service model centered on Namespace, Service, and Instance, enabling fast integration with microservice frameworks. While some concepts like Cluster or Group may be optional, understanding and selectively applying these features helps build reliable, scalable service discovery solutions.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaCloud NativeMicroservicesservice discoveryNacosservice registry
Alibaba Cloud Developer
Written by

Alibaba Cloud Developer

Alibaba's official tech channel, featuring all of its technology innovations.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.