Backend Development 15 min read

Understanding Nacos Service Registration and Discovery in Spring Cloud Microservices

This article explains the fundamentals and implementation of a Nacos service registry in a Spring Cloud microservice architecture, covering registration concepts, building a standalone Nacos server, creating provider and consumer services, and deep-diving into the underlying registration code and HTTP interactions.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Understanding Nacos Service Registration and Discovery in Spring Cloud Microservices

Abstract: The service registry is a crucial component in microservice architectures, providing the foundation for inter‑service communication. This article uses Nacos as an example to explain the basic concepts and principles of service registration.

Through this article, you will learn the complete lifecycle of service registration in microservices, understand the role of a service registry, and gain a comprehensive grasp of the service discovery mechanism in Nacos .

Introduction

Before discussing the "service registry", consider a scenario where a system contains two microservices, ServiceA and ServiceB . Because the services are no longer part of a monolithic application, they cannot be invoked via Bean injection; instead, they must communicate over the network using Http , requiring knowledge of each service's IP and port. Hard‑coding these values works only for a few services and quickly becomes unmanageable as the system grows.

When a dependent service moves or scales, every consumer would need to modify source code and restart, leading to complex configuration management. To avoid this, the concept of a "service registry" emerged.

Service Registry

Before service registries existed, developers had to maintain service IPs manually, which became untenable as the number of services increased. A registry component automatically discovers services and records their information, allowing services to locate each other without hard‑coded addresses.

The primary tasks of a service registry are service registration and service discovery . The following diagram (omitted) illustrates the process.

Building a Registry and Enabling Service Calls

The Nacos registration server can be downloaded from the official website. After extracting the package, run .\startup.cmd -m standalone in the bin directory to start Nacos in standalone mode.

Start Nacos

Access the console at http://192.168.40.1:8848 to verify that the server is running.

Visit the Nacos management console

Next, create two Spring Boot projects: cloud-provider (the service provider) and cloud-consumer (the service consumer). The provider exposes a UserController with a getUserInfo endpoint:

@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping("info/{id}")
    public String getUserInfo(@PathVariable("id") String id) {
        return JSONUtil.toJsonStr(new UserInfo(id, "cloud-provider"));
    }
}

The consumer calls the provider via RestTemplate :

@RestController
@RequestMapping("userConsumers")
public class UserConsumer {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("info/{id}")
    public ResponseEntity
getUserInfo(@PathVariable("id") String id) {
        return restTemplate.getForEntity("http://cloud-provider/user/info/" + id, String.class);
    }
}

The Maven dependencies required for both modules include Spring Boot, Spring Cloud, and Hutool libraries.

Nacos Service Registration Principles

When Nacos‑discovery is added to a project, Spring Boot automatically registers NacosServiceRegistryAutoConfiguration . This configuration creates three beans:

NacosAutoServiceRegistration : Automatically registers the service at application startup.

NacosRegistration : Holds metadata such as service name, instance ID, and host address.

NacosServiceRegistry : Communicates with the Nacos server to perform registration, update, and deregistration operations.

The core registration flow occurs in NacosServiceRegistry.register() :

public void register(Registration registration) {
    // Obtain service properties
    NamingService namingService = namingService();
    String serviceId = registration.getServiceId();
    String group = nacosDiscoveryProperties.getGroup();
    // Build instance object
    Instance instance = getNacosInstanceFromRegistration(registration);
    // Register instance
    namingService.registerInstance(serviceId, group, instance);
    // ... other logic omitted
}

The registerInstance call ultimately sends an HTTP POST to the Nacos endpoint /nacos/v1/ns/instance . The request parameters include namespace, service name, IP, port, weight, health status, and metadata. The HTTP client ( NamingHttpClientProxy ) builds the URL, adds a heartbeat task for ephemeral instances, and retries up to three times on failure.

public void registerService(String serviceName, String groupName, Instance instance) throws NacosException {
    if (instance.isEphemeral()) {
        BeatInfo beatInfo = beatReactor.buildBeatInfo(groupedServiceName, instance);
        beatReactor.addBeatInfo(groupedServiceName, beatInfo);
    }
    Map
params = new HashMap<>(32);
    params.put(CommonParams.NAMESPACE_ID, namespaceId);
    params.put(CommonParams.SERVICE_NAME, groupedServiceName);
    params.put(CommonParams.GROUP_NAME, groupName);
    params.put(CommonParams.CLUSTER_NAME, instance.getClusterName());
    params.put(IP_PARAM, instance.getIp());
    params.put(PORT_PARAM, String.valueOf(instance.getPort()));
    // ... other params
    reqApi(UtilAndComs.nacosUrlInstance, params, HttpMethod.POST);
}

The reqApi method adds the namespace ID, selects a Nacos server from the list, and retries the HTTP call using callServer . If the call succeeds, the response is returned; otherwise, a NacosException is thrown.

Conclusion

This article introduced the role of a service registry in microservices, demonstrated how to set up a standalone Nacos server, built a provider and consumer using Spring Boot, and performed end‑to‑end service registration and invocation. It also dissected the key source code of Nacos registration, revealing that the entire mechanism relies on simple HTTP interactions with the Nacos server.

JavaMicroservicesNacosSpring Bootservice registrationSpring CloudDiscovery
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login 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.