Nacos client library for dynamic service discovery and configuration management in cloud native applications and microservices platforms
npx @tessl/cli install tessl/maven-com-alibaba-nacos--nacos-client@3.0.00
# Nacos Client
1
2
Nacos client library for dynamic service discovery and configuration management in cloud native applications and microservices platforms. Nacos (Dynamic Naming and Configuration Service) provides essential infrastructure capabilities for building scalable, resilient distributed systems with centralized service management and configuration control.
3
4
## Package Information
5
6
- **Package Name**: nacos-client
7
- **Language**: Java
8
- **Package Manager**: Maven
9
- **Group ID**: com.alibaba.nacos
10
- **Artifact ID**: nacos-client
11
- **Installation**:
12
```xml
13
<dependency>
14
<groupId>com.alibaba.nacos</groupId>
15
<artifactId>nacos-client</artifactId>
16
<version>3.0.2</version>
17
</dependency>
18
```
19
20
## Core Imports
21
22
```java
23
import com.alibaba.nacos.api.NacosFactory;
24
import com.alibaba.nacos.api.config.ConfigService;
25
import com.alibaba.nacos.api.naming.NamingService;
26
import com.alibaba.nacos.api.exception.NacosException;
27
```
28
29
Specialized services:
30
```java
31
import com.alibaba.nacos.api.config.ConfigFactory;
32
import com.alibaba.nacos.api.naming.NamingFactory;
33
import com.alibaba.nacos.api.lock.NacosLockFactory;
34
import com.alibaba.nacos.api.lock.LockService;
35
```
36
37
## Basic Usage
38
39
```java
40
import com.alibaba.nacos.api.NacosFactory;
41
import com.alibaba.nacos.api.config.ConfigService;
42
import com.alibaba.nacos.api.naming.NamingService;
43
import com.alibaba.nacos.api.naming.pojo.Instance;
44
import com.alibaba.nacos.api.exception.NacosException;
45
46
import java.util.List;
47
import java.util.Properties;
48
49
public class NacosClientExample {
50
public static void main(String[] args) throws NacosException {
51
// Configure connection properties
52
Properties properties = new Properties();
53
properties.setProperty("serverAddr", "localhost:8848");
54
properties.setProperty("namespace", "public");
55
56
// Configuration Management
57
ConfigService configService = NacosFactory.createConfigService(properties);
58
59
// Get configuration
60
String config = configService.getConfig("example.properties", "DEFAULT_GROUP", 5000);
61
System.out.println("Configuration: " + config);
62
63
// Publish configuration
64
boolean published = configService.publishConfig("example.properties", "DEFAULT_GROUP", "key=value");
65
66
// Service Discovery
67
NamingService namingService = NacosFactory.createNamingService(properties);
68
69
// Register service instance
70
Instance instance = new Instance();
71
instance.setIp("192.168.1.100");
72
instance.setPort(8080);
73
instance.setWeight(1.0);
74
namingService.registerInstance("user-service", instance);
75
76
// Discover service instances
77
List<Instance> instances = namingService.getAllInstances("user-service");
78
System.out.println("Found " + instances.size() + " instances");
79
}
80
}
81
```
82
83
## Architecture
84
85
Nacos client provides a multi-service architecture with clear separation of concerns:
86
87
- **Configuration Service**: Centralized configuration management with real-time updates, change listeners, and atomic operations
88
- **Naming Service**: Service registration, discovery, and health monitoring with support for clusters and load balancing
89
- **Lock Service**: Distributed locking for coordination across microservices
90
- **Event System**: Reactive listeners for configuration changes and service instance updates
91
92
The client uses a factory pattern for service creation, supports multiple server addresses for high availability, and provides extensive customization through properties configuration. All services support namespace isolation for multi-tenant environments.
93
94
## Capabilities
95
96
### Configuration Management
97
98
Centralized configuration management with real-time updates, change listeners, atomic CAS operations, and fuzzy pattern-based watching. Supports multiple configuration formats and provides filtering mechanisms for request/response processing.
99
100
```java { .api }
101
public interface ConfigService {
102
String getConfig(String dataId, String group, long timeoutMs) throws NacosException;
103
boolean publishConfig(String dataId, String group, String content) throws NacosException;
104
boolean removeConfig(String dataId, String group) throws NacosException;
105
void addListener(String dataId, String group, Listener listener) throws NacosException;
106
void removeListener(String dataId, String group, Listener listener);
107
}
108
```
109
110
[Configuration Management](./configuration.md)
111
112
### Service Discovery and Registration
113
114
Service registration, discovery, and health monitoring with support for weighted load balancing, cluster management, and real-time instance updates. Includes batch operations and event-driven programming model.
115
116
```java { .api }
117
public interface NamingService {
118
void registerInstance(String serviceName, Instance instance) throws NacosException;
119
void deregisterInstance(String serviceName, Instance instance) throws NacosException;
120
List<Instance> getAllInstances(String serviceName) throws NacosException;
121
List<Instance> selectInstances(String serviceName, boolean healthy) throws NacosException;
122
Instance selectOneHealthyInstance(String serviceName) throws NacosException;
123
void subscribe(String serviceName, EventListener listener) throws NacosException;
124
List<ServiceInfo> getSubscribeServices() throws NacosException;
125
}
126
```
127
128
[Service Discovery](./service-discovery.md)
129
130
### Distributed Locking
131
132
Distributed locking capabilities for coordination and synchronization across microservices. Supports lock expiration, try-lock operations, and remote lock management.
133
134
```java { .api }
135
public interface LockService {
136
Boolean lock(LockInstance instance) throws NacosException;
137
Boolean unLock(LockInstance instance) throws NacosException;
138
Boolean remoteTryLock(LockInstance instance) throws NacosException;
139
Boolean remoteReleaseLock(LockInstance instance) throws NacosException;
140
void shutdown() throws NacosException;
141
}
142
```
143
144
[Distributed Locking](./distributed-locking.md)
145
146
### Factory and Utilities
147
148
Service factory methods, utility classes, annotation support, and comprehensive exception handling. Includes capability management and extensive configuration options.
149
150
```java { .api }
151
public class NacosFactory {
152
public static ConfigService createConfigService(Properties properties) throws NacosException;
153
public static NamingService createNamingService(Properties properties) throws NacosException;
154
public static LockService createLockService(Properties properties) throws NacosException;
155
}
156
```
157
158
[Factory and Utilities](./factory-utilities.md)
159
160
## Types
161
162
### Core Data Models
163
164
```java { .api }
165
public class Instance {
166
private String instanceId;
167
private String ip;
168
private int port;
169
private double weight;
170
private boolean healthy;
171
private boolean enabled;
172
private boolean ephemeral;
173
private String clusterName;
174
private String serviceName;
175
private Map<String, String> metadata;
176
177
// Constructor and getter/setter methods
178
public Instance();
179
public String getIp();
180
public void setIp(String ip);
181
public int getPort();
182
public void setPort(int port);
183
public double getWeight();
184
public void setWeight(double weight);
185
public boolean isHealthy();
186
public void setHealthy(boolean healthy);
187
public Map<String, String> getMetadata();
188
public void setMetadata(Map<String, String> metadata);
189
}
190
191
public class ServiceInfo {
192
private String name;
193
private String groupName;
194
private String clusters;
195
private List<Instance> hosts;
196
private long cacheMillis;
197
private long lastRefTime;
198
199
// Constructor and getter/setter methods
200
public String getName();
201
public void setName(String name);
202
public List<Instance> getHosts();
203
public void setHosts(List<Instance> hosts);
204
}
205
206
public class NacosException extends Exception {
207
public static final int CLIENT_INVALID_PARAM = 400;
208
public static final int CLIENT_OVER_THRESHOLD = 503;
209
public static final int SERVER_ERROR = 500;
210
public static final int BAD_GATEWAY = 502;
211
public static final int RESOURCE_NOT_FOUND = 404;
212
213
public NacosException(int errCode, String errMsg);
214
public int getErrCode();
215
public String getErrMsg();
216
}
217
```
218
219
### Configuration Events
220
221
```java { .api }
222
public class ConfigChangeEvent {
223
private String dataId;
224
private String group;
225
private String namespace;
226
private String content;
227
private String oldContent;
228
private PropertyChangeType changeType;
229
230
public String getDataId();
231
public String getGroup();
232
public String getContent();
233
public PropertyChangeType getChangeType();
234
}
235
236
public interface Listener {
237
void receiveConfigInfo(String configInfo);
238
Executor getExecutor();
239
}
240
```
241
242
### Constants and Enums
243
244
```java { .api }
245
public enum ConfigType {
246
PROPERTIES, XML, JSON, TEXT, HTML, YAML, TOML, UNSET
247
}
248
249
public enum PropertyChangeType {
250
ADDED, MODIFIED, DELETED
251
}
252
253
public class PropertyKeyConst {
254
public static final String SERVER_ADDR = "serverAddr";
255
public static final String NAMESPACE = "namespace";
256
public static final String USERNAME = "username";
257
public static final String PASSWORD = "password";
258
public static final String CLUSTER_NAME = "clusterName";
259
public static final String ENCODE = "encode";
260
}
261
```