Mastering Configuration Centers: From Local Files to Nacos in Microservices
This article explains how configuration management evolves from simple local files in monolithic applications to centralized, dynamic configuration centers like Nacos for microservices, covering code examples, registration, deregistration, viewing, change subscription, and guidance on choosing a service registry.
1. Local Configuration
In Spring Boot you can place configuration items in Java classes or load them from YAML files.
public class AppConfig {
public static final String static_SUCCESS_CODE = "0000";
public static final String static_ERROR_CODE = "0001";
}Or use @Value to inject values from application.yml:
@Component
public class HttpConfig {
public static String config_CORE_POOL_SIZE;
@Value("${async.corePoolSize}")
public void setSaveUrl(String corePoolSize) {
HttpConfig.config_CORE_POOL_SIZE = corePoolSize;
}
}Changing these configurations requires stopping the application, editing the files, and restarting, which is error‑prone for large numbers of settings.
2. Configuration Center
A Configuration Center centralizes management of application settings such as database connections, external service addresses, log levels, and timeouts, improving deployment flexibility and maintainability.
When a service starts, it can automatically pull required configuration items from the center, and updates are fetched dynamically without redeploying the service.
2.1 Example with Nacos
Configuration is usually placed in bootstrap.yml.
The Bootstrap Context loads and parses external configuration sources during initialization.
Bootstrap properties have high priority and are not overridden by local configuration by default.
Application then reads application.yml, merges configurations, and starts.
Only core configurations that need hot updates should be managed by Nacos; stable settings can remain local.
2.2 Pull Mode
Nacos uses a pull model where the client long‑polls the server to check for configuration changes.
The client sends a long‑poll request listening for changes of a specific dataId+group.
The server holds the request until a change occurs or a timeout (e.g., 29.5 seconds) expires.
If no change occurs within the timeout, the server returns a response anyway.
If a change occurs, the server pushes the new data to the client.
2.3 Nacos as a Service Registry
Nacos can also act as a simple service registry where services register themselves and clients retrieve service addresses before invoking them.
Services maintain a heartbeat with Nacos every 5 seconds. If Nacos does not receive a heartbeat within 5 seconds, the service is considered down and is deregistered. After 15 seconds without a heartbeat, the service is marked unhealthy; after 30 seconds it is removed.
If a service stops sending heartbeats for 5 seconds, Nacos marks it offline.
After 15 seconds without a heartbeat, the service’s healthy flag becomes false, preventing client calls.
After 30 seconds, Nacos removes the service entirely.
3. Features Provided by a Configuration Center
Configuration Item Management : Add, publish, modify, group, version control, hot release, gray release, environment isolation, API and UI.
Permission Control : Read and write access control for configuration items.
Operation Auditing : Record user actions.
Configuration Change Detection : Real‑time monitoring of new or modified items.
Configuration Push : Publish‑/subscribe‑style push to consumers.
Historical Version Management : Store, query, compare, and roll back versions.
Gray Release : Deploy new configurations to a subset of environments first.
Change Auditing : Log every modification for traceability.
These capabilities reduce the cost and risk of managing configuration in distributed systems.
4. Operating a Configuration Center
4.1 Configuration Registration
Register a configuration item via the center’s SDK:
import com.configcenter.sdk.ConfigCenterClient;
import com.configcenter.sdk.exception.ConfigCenterException;
import com.configcenter.sdk.model.Configuration;
public class ConfigurationRegistration {
public static void main(String[] args) {
String serverUrl = "configcenter_server_url";
String authToken = "your_auth_token";
Configuration configuration = new Configuration();
configuration.setId("your_configuration_id");
configuration.setKey("your_configuration_key");
configuration.setValue("your_configuration_value");
try {
ConfigCenterClient client = ConfigCenterClient.init(serverUrl, authToken);
boolean success = client.registerConfiguration(configuration);
if (success) {
System.out.println("Configuration registration succeeded");
} else {
System.out.println("Configuration registration failed");
}
} catch (ConfigCenterException e) {
System.out.println("Registration exception: " + e.getMessage());
e.printStackTrace();
}
}
}4.2 Configuration Deregistration
Remove a configuration item when it is no longer needed:
import com.configcenter.sdk.ConfigCenterClient;
import com.configcenter.sdk.exception.ConfigCenterException;
public class ConfigurationDeregistration {
public static void main(String[] args) {
String serverUrl = "configcenter_server_url";
String authToken = "your_auth_token";
String configurationId = "your_configuration_id";
try {
ConfigCenterClient client = ConfigCenterClient.init(serverUrl, authToken);
boolean success = client.deregisterConfiguration(configurationId);
if (success) {
System.out.println("Configuration deregistration succeeded");
} else {
System.out.println("Configuration deregistration failed");
}
} catch (ConfigCenterException e) {
System.out.println("Deregistration exception: " + e.getMessage());
e.printStackTrace();
}
}
}4.3 Configuration Viewing
Retrieve and display a configuration item:
import com.configcenter.sdk.ConfigCenterClient;
import com.configcenter.sdk.exception.ConfigCenterException;
import com.configcenter.sdk.model.Configuration;
public class ConfigurationViewer {
public static void main(String[] args) {
String serverUrl = "configcenter_server_url";
String authToken = "your_auth_token";
String configurationId = "your_configuration_id";
try {
ConfigCenterClient client = ConfigCenterClient.init(serverUrl, authToken);
Configuration configuration = client.getConfiguration(configurationId);
if (configuration != null) {
System.out.println("ID: " + configuration.getId());
System.out.println("Key: " + configuration.getKey());
System.out.println("Value: " + configuration.getValue());
} else {
System.out.println("Configuration not found");
}
} catch (ConfigCenterException e) {
System.out.println("View exception: " + e.getMessage());
e.printStackTrace();
}
}
}4.4 Configuration Change Subscription
Subscribe to configuration updates so the application can react in real time:
import com.configcenter.sdk.ConfigCenterClient;
import com.configcenter.sdk.exception.ConfigCenterException;
import com.configcenter.sdk.listener.ConfigurationChangeListener;
import com.configcenter.sdk.model.Configuration;
public class ConfigurationSubscriber {
public static void main(String[] args) {
// Assume serverUrl and authToken are defined
ConfigurationChangeListener listener = new ConfigurationChangeListener() {
@Override
public void onConfigurationChanged(Configuration configuration) {
System.out.println("Configuration changed: " + configuration.getKey() + " = " + configuration.getValue());
// Update cache, reload config, etc.
}
};
try {
ConfigCenterClient client = ConfigCenterClient.init(serverUrl, authToken);
client.subscribeToConfigurationChanges(filter, listener);
} catch (ConfigCenterException e) {
System.out.println("Subscription exception: " + e.getMessage());
e.printStackTrace();
}
}
}5. Mainstream Microservice Registration Centers and Selection Guidance
5.1 Factors to Consider
Features and Capabilities : Choose based on required functions such as pure service discovery versus combined configuration management.
Performance and Stability : Evaluate latency, throughput, and fault tolerance.
Ease of Use and Developer Experience : Good documentation, client libraries, and tooling matter.
Community Support and Ecosystem : Active community and ecosystem provide extensions and help.
Security and Compliance : Ensure the registry meets security requirements.
5.2 Popular Registries
Eureka : Netflix’s solution, integrates tightly with Spring Cloud, offers high availability and eventual consistency.
Consul : Written in Go, provides strong consistency, multi‑datacenter support, and a rich feature set.
Zookeeper : Originally a coordination service, offers strong consistency and high availability but requires custom discovery logic.
Nacos : Alibaba’s open‑source project, supports DNS‑ and RPC‑based discovery and dynamic configuration, easy to use with Spring Cloud.
5.3 How to Choose
If you are already using Spring Cloud, Eureka is a natural fit.
For cross‑platform needs and strong consistency, Consul is a solid choice.
If your stack already relies on Apache projects, Zookeeper may be appropriate.
If you prefer a simple solution that combines service discovery with dynamic configuration, consider Nacos.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
