# How KCloud-Platform-IoT Uses Nacos for Service Discovery and Configuration Management

> Explore how KCloud-Platform-IoT utilizes Nacos for seamless service discovery and efficient configuration management. Learn about its integration with Spring Cloud Alibaba and custom helper libraries.

- Repository: [laokou/kcloud-platform-iot](https://github.com/koushenhai/kcloud-platform-iot)
- Tags: how-to-guide
- Published: 2026-03-05

---

**KCloud-Platform-IoT leverages Alibaba Nacos 3.1.1 as its unified registry and configuration center through Spring Cloud Alibaba integration and a custom `laokou-common-nacos` helper library.**

KCloud-Platform-IoT is an open-source IoT microservices platform that centralizes infrastructure concerns using Alibaba Nacos. The architecture implements **Nacos for service discovery and configuration management** across all microservices, combining Spring Cloud Alibaba auto-configuration with custom utility classes for fine-grained control.

## Nacos Integration Architecture and Dependencies

The platform standardizes on **Nacos 3.1.1** across the entire service mesh. In the root [`pom.xml`](https://github.com/koushenhai/kcloud-platform-iot/blob/main/pom.xml), the version is centralized and the `nacos-all` artifact provides the complete client SDK:

```xml
<!--nacos版本-->
<nacos.version>3.1.1</nacos.version>
…
<dependency>
    <groupId>com.alibaba.nacos</groupId>
    <artifactId>nacos-all</artifactId>
    <version>${nacos.version}</version>
</dependency>

```

Source: [`pom.xml`](https://github.com/koushenhai/kcloud-platform-iot/blob/main/pom.xml) in the repository root defines this dependency management.

## The Custom Nacos Helper Module (`laokou-common-nacos`)

Rather than scattering raw Nacos SDK calls throughout business code, the platform abstracts common operations into a centralized module. This approach ensures consistent error handling and simplifies upgrades.

### Configuration Management Utilities

The **ConfigUtils.java** class located at [`laokou-common/laokou-common-nacos/src/main/java/org/laokou/common/nacos/util/ConfigUtils.java`](https://github.com/koushenhai/kcloud-platform-iot/blob/main/laokou-common/laokou-common-nacos/src/main/java/org/laokou/common/nacos/util/ConfigUtils.java) wraps `NacosFactory.createConfigService(..)`. This utility returns pre-configured `ConfigService` instances for programmatic configuration access when annotation-driven injection is insufficient.

### Service Discovery Utilities

**NamingUtils.java** (found in [`laokou-common/laokou-common-nacos/src/main/java/org/laokou/common/nacos/util/NamingUtils.java`](https://github.com/koushenhai/kcloud-platform-iot/blob/main/laokou-common/laokou-common-nacos/src/main/java/org/laokou/common/nacos/util/NamingUtils.java)) provides thin wrappers around the Nacos naming API. It exposes methods for instance registration, deregistration, and health queries that services invoke for manual lifecycle management.

### Debugging and Router Inspection

The module includes **EnablePrintRouter.java** (in the annotation package) along with its handler. This Spring Boot annotation registers a **router-info endpoint** that exposes real-time Nacos-based routing decisions, enabling operators to debug instance selection logic.

### Load Balancer Integration

The platform implements a custom Nacos-backed load balancer through classes like [`NacosLoadBalancerClientConfiguration.java`](https://github.com/koushenhai/kcloud-platform-iot/blob/main/NacosLoadBalancerClientConfiguration.java). This integration replaces the default Spring Cloud LoadBalancer with one that resolves instances directly from the Nacos naming service, supporting weighted routing and health-aware selection.

## Implementing Service Discovery with Nacos

Each microservice configures Nacos discovery through standardized YAML blocks. The **IoT service** demonstrates this pattern in [`laokou-service/laokou-iot/laokou-iot-start/src/main/resources/application.yml`](https://github.com/koushenhai/kcloud-platform-iot/blob/main/laokou-service/laokou-iot/laokou-iot-start/src/main/resources/application.yml):

```yaml
spring:
  cloud:
    nacos:
      discovery:
        server-addr: ${NACOS_DISCOVERY_ADDRESS:nacos:8848,nacos:8858,nacos:8868}
        username: ${NACOS_USERNAME:nacos}
        password: ${NACOS_PASSWORD:nacos}

```

At runtime, Spring Cloud Alibaba auto-configuration handles registration implicitly via `NamingUtils` methods. For programmatic control, developers invoke the utility directly:

```java
import org.laokou.common.nacos.util.NamingUtils;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.exception.NacosException;

public class DiscoveryDemo {
    public static void main(String[] args) throws NacosException {
        Instance instance = new Instance();
        instance.setIp("192.168.1.101");
        instance.setPort(8080);
        instance.setServiceName("iot-service");
        instance.setHealthy(true);
        
        NamingUtils.registerInstance(instance);
        System.out.println("Instance registered with Nacos");
    }
}

```

## Dynamic Configuration Management with Nacos

Configuration management separates config and discovery addresses for flexible deployment topologies. The IoT service defines its config endpoint in the same [`application.yml`](https://github.com/koushenhai/kcloud-platform-iot/blob/main/application.yml):

```yaml
spring:
  cloud:
    nacos:
      config:
        server-addr: ${NACOS_CONFIG_ADDRESS:nacos:8848,nacos:8858,nacos:8868}
        namespace: ${NACOS_NAMESPACE:public}
        file-extension: yaml
        refresh-enabled: true
        group: ${NACOS_GROUP:IOT_GROUP}

```

Services load multiple configuration data IDs using the `optional:nacos:` URI scheme. For example, the **Auth service** in [`laokou-service/laokou-auth/laokou-auth-start/src/main/resources/application.yml`](https://github.com/koushenhai/kcloud-platform-iot/blob/main/laokou-service/laokou-auth/laokou-auth-start/src/main/resources/application.yml) loads additional security configurations:

```yaml
spring:
  config:
    import: optional:nacos:laokou-auth.yaml?refreshEnabled=true&group=${NACOS_GROUP:IOT_GROUP}

```

For raw SDK access when configuration listeners are required programmatically, use **ConfigUtils**:

```java
import org.laokou.common.nacos.util.ConfigUtils;
import com.alibaba.nacos.api.config.ConfigService;

public class RemoteConfigDemo {
    public static void main(String[] args) throws Exception {
        String serverAddr = "nacos:8848";
        ConfigService configService = ConfigUtils.createConfigService(serverAddr);
        
        String content = configService.getConfig("my-config.yaml", "DEFAULT_GROUP", 5000);
        System.out.println("Remote config: " + content);
    }
}

```

## Resolving Nacos Logging Conflicts

Nacos ships with embedded Log4j2 configurations that can suppress application logs. Every service in KCloud-Platform-IoT disables Nacos's default logging early in the bootstrap phase. In [`IotApp.java`](https://github.com/koushenhai/kcloud-platform-iot/blob/main/IotApp.java) and other main application classes, the system property is set before Spring initialization:

```java
// 配置关闭nacos日志，因为nacos的log4j2导致本项目的日志不输出的问题
System.setProperty("nacos.logging.default.config.enabled", "false");

```

Source: [`laokou-service/laokou-iot/laokou-iot-start/src/main/java/org/laokou/iot/IotApp.java`](https://github.com/koushenhai/kcloud-platform-iot/blob/main/laokou-service/laokou-iot/laokou-iot-start/src/main/java/org/laokou/iot/IotApp.java)

## Client-Side Load Balancing Implementation

The platform utilizes the custom Nacos load balancer for inter-service communication. When calling the IoT service from another microservice, the Spring Cloud LoadBalancer client resolves the instance through Nacos:

```java
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CallIotService {
    @Autowired
    private LoadBalancerClient loadBalancer;

    public void invoke() {
        ServiceInstance si = loadBalancer.choose("iot-service");
        String url = "http://" + si.getHost() + ":" + si.getPort() + "/api/health";
        // Proceed with HTTP call using RestTemplate or WebClient
    }
}

```

This implementation queries the Nacos naming service for healthy instances of `iot-service` and applies the platform's custom routing strategy.

## Summary

- **KCloud-Platform-IoT** centralizes microservice coordination using **Nacos 3.1.1** for both service discovery and configuration management, as defined in the root [`pom.xml`](https://github.com/koushenhai/kcloud-platform-iot/blob/main/pom.xml).
- The custom **`laokou-common-nacos`** module abstracts Nacos SDK complexity through **ConfigUtils** and **NamingUtils** wrappers located in `laokou-common/laokou-common-nacos/src/main/java/org/laokou/common/nacos/util/`.
- Services configure discovery and config separately via `spring.cloud.nacos.discovery` and `spring.cloud.nacos.config` blocks in their respective [`application.yml`](https://github.com/koushenhai/kcloud-platform-iot/blob/main/application.yml) files, supporting multi-cluster deployments.
- The platform implements a **custom Nacos load balancer** that integrates with Spring Cloud LoadBalancer for health-aware instance selection.
- All services disable Nacos's default Log4j2 configuration by setting `nacos.logging.default.config.enabled` to `false` in their main application entry points to prevent logging conflicts.

## Frequently Asked Questions

### What version of Nacos does KCloud-Platform-IoT use?

The platform standardizes on **Nacos 3.1.1**, defined centrally in the root [`pom.xml`](https://github.com/koushenhai/kcloud-platform-iot/blob/main/pom.xml) and imported through the `nacos-all` artifact. This version is used consistently across all microservices to ensure client-server compatibility and access to the latest naming and configuration APIs.

### How does the platform handle dynamic configuration updates?

Configuration refresh is enabled via `refresh-enabled: true` in the Nacos config block. Additionally, the `spring.config.import` property supports the `refreshEnabled` parameter for specific data IDs, allowing Spring components to receive `@RefreshScope` events and update properties without application restart.

### Why does KCloud-Platform-IoT disable Nacos's default logging?

Nacos includes its own Log4j2 configuration files that can override the platform's logging framework, causing application logs to stop appearing. By setting `System.setProperty("nacos.logging.default.config.enabled", "false")` in each service's main method (such as [`IotApp.java`](https://github.com/koushenhai/kcloud-platform-iot/blob/main/IotApp.java)), the platform ensures its unified logging strategy remains intact and log output is not suppressed.

### Can services use Nacos for service discovery without Spring Cloud Alibaba auto-configuration?

Yes. While the platform primarily relies on Spring Cloud Alibaba auto-configuration, the **NamingUtils** class provides direct access to the Nacos naming API. Developers can programmatically register or deregister instances using `NamingUtils.registerInstance()` when custom registration logic or manual health checks are required outside the standard lifecycle.