0
# Factory and Utilities
1
2
Service factory methods, utility classes, annotation support, and comprehensive exception handling. Includes capability management and extensive configuration options for all Nacos client services.
3
4
## Capabilities
5
6
### Primary Service Factory
7
8
Main entry point for creating all Nacos services with unified configuration.
9
10
```java { .api }
11
public class NacosFactory {
12
// Configuration Service creation
13
public static ConfigService createConfigService(Properties properties) throws NacosException;
14
public static ConfigService createConfigService(String serverAddr) throws NacosException;
15
16
// Naming Service creation
17
public static NamingService createNamingService(Properties properties) throws NacosException;
18
public static NamingService createNamingService(String serverAddr) throws NacosException;
19
20
// Naming Maintain Service creation (Deprecated)
21
public static NamingMaintainService createMaintainService(Properties properties) throws NacosException;
22
public static NamingMaintainService createMaintainService(String serverAddr) throws NacosException;
23
24
// Lock Service creation
25
public static LockService createLockService(Properties properties) throws NacosException;
26
public static LockService createLockService(String serverAddr) throws NacosException;
27
}
28
```
29
30
#### Usage Examples
31
32
```java
33
import com.alibaba.nacos.api.NacosFactory;
34
import com.alibaba.nacos.api.config.ConfigService;
35
import com.alibaba.nacos.api.naming.NamingService;
36
import com.alibaba.nacos.api.lock.LockService;
37
38
// Simple server address configuration
39
ConfigService configService = NacosFactory.createConfigService("localhost:8848");
40
NamingService namingService = NacosFactory.createNamingService("localhost:8848");
41
42
// Advanced properties configuration
43
Properties properties = new Properties();
44
properties.setProperty("serverAddr", "192.168.1.100:8848,192.168.1.101:8848");
45
properties.setProperty("namespace", "dev-environment");
46
properties.setProperty("username", "nacos");
47
properties.setProperty("password", "nacos123");
48
properties.setProperty("clusterName", "beijing");
49
50
ConfigService configSvc = NacosFactory.createConfigService(properties);
51
NamingService namingSvc = NacosFactory.createNamingService(properties);
52
LockService lockSvc = NacosFactory.createLockService(properties);
53
```
54
55
### Specialized Factories
56
57
Individual factories for specific service types with same configuration options.
58
59
```java { .api }
60
public class ConfigFactory {
61
public static ConfigService createConfigService(Properties properties) throws NacosException;
62
public static ConfigService createConfigService(String serverAddr) throws NacosException;
63
}
64
65
public class NamingFactory {
66
public static NamingService createNamingService(Properties properties) throws NacosException;
67
public static NamingService createNamingService(String serverAddr) throws NacosException;
68
}
69
70
public class NamingMaintainFactory {
71
@Deprecated
72
public static NamingMaintainService createMaintainService(Properties properties) throws NacosException;
73
@Deprecated
74
public static NamingMaintainService createMaintainService(String serverAddr) throws NacosException;
75
}
76
77
public class NacosLockFactory {
78
public static LockService createLockService(Properties properties) throws NacosException;
79
public static LockService createLockService(String serverAddr) throws NacosException;
80
}
81
```
82
83
### Configuration Properties
84
85
Comprehensive configuration options for all Nacos client services.
86
87
```java { .api }
88
public class PropertyKeyConst {
89
// Server connection
90
public static final String SERVER_ADDR = "serverAddr";
91
public static final String CONTEXT_PATH = "contextPath";
92
public static final String CLUSTER_NAME = "clusterName";
93
public static final String ENCODE = "encode";
94
public static final String NAMESPACE = "namespace";
95
96
// Authentication
97
public static final String USERNAME = "username";
98
public static final String PASSWORD = "password";
99
public static final String ACCESS_KEY = "accessKey";
100
public static final String SECRET_KEY = "secretKey";
101
102
// SSL/TLS
103
public static final String IS_USE_CLOUD_NAMESPACE_PARSING = "isUseCloudNamespaceParsing";
104
public static final String IS_USE_ENDPOINT_PARSING_RULE = "isUseEndpointParsingRule";
105
106
// Performance tuning
107
public static final String NAMING_LOAD_CACHE_AT_START = "namingLoadCacheAtStart";
108
public static final String NAMING_CLIENT_BEAT_THREAD_COUNT = "namingClientBeatThreadCount";
109
public static final String NAMING_POLLING_THREAD_COUNT = "namingPollingThreadCount";
110
public static final String NAMING_REQUEST_DOMAIN_RETRY_COUNT = "namingRequestDomainMaxRetryCount";
111
public static final String NAMING_PUSH_EMPTY_PROTECTION = "namingPushEmptyProtection";
112
113
// Configuration specific
114
public static final String CONFIG_LONG_POLL_TIMEOUT = "configLongPollTimeout";
115
public static final String CONFIG_RETRY_TIME = "configRetryTime";
116
public static final String MAX_RETRY = "maxRetry";
117
public static final String ENABLE_REMOTE_SYNC_CONFIG = "enableRemoteSyncConfig";
118
119
// Connection pooling
120
public static final String CONN_POOL_SIZE = "connPoolSize";
121
public static final String CONN_POOL_TIMEOUT = "connPoolTimeout";
122
public static final String CONN_POOL_ALIVE = "connPoolAlive";
123
}
124
```
125
126
#### Configuration Examples
127
128
```java
129
// High availability configuration
130
Properties props = new Properties();
131
props.setProperty(PropertyKeyConst.SERVER_ADDR, "nacos1:8848,nacos2:8848,nacos3:8848");
132
props.setProperty(PropertyKeyConst.NAMESPACE, "production");
133
props.setProperty(PropertyKeyConst.CLUSTER_NAME, "us-west");
134
135
// Authentication configuration
136
props.setProperty(PropertyKeyConst.USERNAME, "admin");
137
props.setProperty(PropertyKeyConst.PASSWORD, "admin123");
138
139
// Performance tuning
140
props.setProperty(PropertyKeyConst.NAMING_CLIENT_BEAT_THREAD_COUNT, "5");
141
props.setProperty(PropertyKeyConst.NAMING_POLLING_THREAD_COUNT, "10");
142
props.setProperty(PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT, "30000");
143
144
// Connection pooling
145
props.setProperty(PropertyKeyConst.CONN_POOL_SIZE, "20");
146
props.setProperty(PropertyKeyConst.CONN_POOL_TIMEOUT, "3000");
147
148
ConfigService configService = NacosFactory.createConfigService(props);
149
```
150
151
### System Properties
152
153
System-level property keys for global configuration.
154
155
```java { .api }
156
public class SystemPropertyKeyConst {
157
// JVM system properties
158
public static final String IS_USE_CLOUD_NAMESPACE_PARSING = "IS_USE_CLOUD_NAMESPACE_PARSING";
159
public static final String IS_USE_ENDPOINT_PARSING_RULE = "IS_USE_ENDPOINT_PARSING_RULE";
160
public static final String NAMING_SERVER_PORT = "NAMING_SERVER_PORT";
161
public static final String CONFIG_SERVER_PORT = "CONFIG_SERVER_PORT";
162
163
// Environment specific
164
public static final String JM_SNAPSHOT_PATH = "JM.SNAPSHOT.PATH";
165
public static final String JM_LOG_PATH = "JM.LOG.PATH";
166
}
167
```
168
169
### Exception Hierarchy
170
171
Comprehensive exception handling for all Nacos operations.
172
173
```java { .api }
174
// Main checked exception
175
public class NacosException extends Exception {
176
// Error codes
177
public static final int CLIENT_INVALID_PARAM = 400;
178
public static final int CLIENT_OVER_THRESHOLD = 503;
179
public static final int CLIENT_DISCONNECT_FROM_SERVER = -1001;
180
public static final int SERVER_ERROR = 500;
181
public static final int BAD_GATEWAY = 502;
182
public static final int OVER_THRESHOLD = 503;
183
public static final int RESOURCE_NOT_FOUND = 404;
184
public static final int CLIENT_ERROR = -1000;
185
public static final int CONFLICT = 409;
186
public static final int ACCESS_DENIED = 403;
187
public static final int INVALID_SERVER_STATUS = -1002;
188
189
public NacosException(int errCode, String errMsg);
190
public NacosException(int errCode, String errMsg, Throwable cause);
191
192
public int getErrCode();
193
public String getErrMsg();
194
}
195
196
// Runtime exceptions
197
public class NacosRuntimeException extends RuntimeException {
198
public NacosRuntimeException(String message);
199
public NacosRuntimeException(String message, Throwable cause);
200
}
201
202
public class NacosLoadException extends NacosRuntimeException {
203
public NacosLoadException(String message);
204
public NacosLoadException(String message, Throwable cause);
205
}
206
207
public class NacosSerializationException extends NacosRuntimeException {
208
public NacosSerializationException(String message);
209
public NacosSerializationException(String message, Throwable cause);
210
}
211
212
public class NacosDeserializationException extends NacosRuntimeException {
213
public NacosDeserializationException(String message);
214
public NacosDeserializationException(String message, Throwable cause);
215
}
216
217
// API-specific exception
218
public class NacosApiException extends NacosException {
219
public NacosApiException(int errCode, String errMsg);
220
public NacosApiException(int errCode, String errMsg, Throwable cause);
221
}
222
```
223
224
### Common Constants
225
226
Standard constants used across all Nacos services.
227
228
```java { .api }
229
public class Constants {
230
// Default values
231
public static final String DEFAULT_GROUP = "DEFAULT_GROUP";
232
public static final String DEFAULT_NAMESPACE_ID = "";
233
public static final String CLIENT_VERSION = "3.0.2";
234
235
// Separators and patterns
236
public static final String WORD_SEPARATOR = "-";
237
public static final String LINE_SEPARATOR = Character.toString((char) 1);
238
public static final String BASE_PATH = "/nacos";
239
public static final String ANY_PATTERN = "*";
240
241
// Timeout values
242
public static final int DEFAULT_TIMEOUT = 3000;
243
public static final long DEFAULT_HEART_BEAT_TIMEOUT = 15000L;
244
public static final long DEFAULT_IP_DELETE_TIMEOUT = 30000L;
245
246
// Encoding
247
public static final String ENCODE_UTF8 = "UTF-8";
248
public static final String ENCODE_GBK = "GBK";
249
250
// HTTP headers
251
public static final String CLIENT_VERSION_HEADER = "Client-Version";
252
public static final String USER_AGENT_HEADER = "User-Agent";
253
}
254
255
public class ResponseCode {
256
public static final int SUCCESS = 200;
257
public static final int FAIL = 500;
258
public static final int UNAUTHORIZED = 401;
259
public static final int FORBIDDEN = 403;
260
public static final int NOT_FOUND = 404;
261
public static final int INTERNAL_ERROR = 500;
262
public static final int BAD_GATEWAY = 502;
263
public static final int SERVICE_UNAVAILABLE = 503;
264
}
265
266
public enum NodeState {
267
UP("UP"),
268
DOWN("DOWN"),
269
STARTING("STARTING"),
270
SUSPECT("SUSPECT");
271
272
private final String state;
273
274
NodeState(String state) {
275
this.state = state;
276
}
277
278
public String getState();
279
}
280
```
281
282
### Annotation Support
283
284
Comprehensive annotation support for dependency injection and configuration binding.
285
286
```java { .api }
287
// Dependency injection annotations
288
@Target({ElementType.FIELD, ElementType.METHOD})
289
@Retention(RetentionPolicy.RUNTIME)
290
public @interface NacosInjected {
291
// Properties for service creation
292
NacosProperties[] properties() default {};
293
}
294
295
@Target({ElementType.TYPE, ElementType.METHOD})
296
@Retention(RetentionPolicy.RUNTIME)
297
public @interface NacosApi {
298
String value() default "";
299
}
300
301
@Repeatable(NacosProperties.List.class)
302
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
303
@Retention(RetentionPolicy.RUNTIME)
304
public @interface NacosProperties {
305
String prefix() default "";
306
String[] value() default {};
307
308
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
309
@Retention(RetentionPolicy.RUNTIME)
310
@interface List {
311
NacosProperties[] value();
312
}
313
}
314
```
315
316
### Client Capabilities
317
318
Client and server capability management for feature negotiation.
319
320
```java { .api }
321
public class ClientAbilities {
322
private Map<AbilityKey, Boolean> abilities;
323
324
public ClientAbilities();
325
326
public boolean isSupported(AbilityKey abilityKey);
327
public void setSupported(AbilityKey abilityKey, boolean supported);
328
public Map<AbilityKey, Boolean> getAbilities();
329
}
330
331
public class ServerAbilities {
332
private Map<AbilityKey, Boolean> abilities;
333
334
public ServerAbilities();
335
336
public boolean isSupported(AbilityKey abilityKey);
337
public void setSupported(AbilityKey abilityKey, boolean supported);
338
public Map<AbilityKey, Boolean> getAbilities();
339
}
340
341
// Capability identifiers
342
public enum AbilityKey {
343
SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC("supportPersistentInstanceByGrpc"),
344
SERVER_SUPPORT_REMOTE_CONNECTION("supportRemoteConnection"),
345
SERVER_SUPPORT_CONFIG_FUZZY_WATCH("supportConfigFuzzyWatch"),
346
SERVER_SUPPORT_NAMING_FUZZY_WATCH("supportNamingFuzzyWatch"),
347
SDK_CLIENT_SUPPORT_FUZZY_WATCH("supportFuzzyWatch");
348
349
private final String name;
350
351
AbilityKey(String name) {
352
this.name = name;
353
}
354
355
public String getName();
356
}
357
358
// Capability states
359
public enum AbilityStatus {
360
SUPPORTED("supported"),
361
NOT_SUPPORTED("not_supported"),
362
UNKNOWN("unknown");
363
364
private final String status;
365
366
AbilityStatus(String status) {
367
this.status = status;
368
}
369
370
public String getStatus();
371
}
372
```
373
374
### Utility Classes
375
376
Common utility functions for validation, parameter handling, and environment setup.
377
378
```java { .api }
379
public class ValidatorUtils {
380
// Parameter validation
381
public static void checkInitParam(Properties properties) throws NacosException;
382
public static void checkServiceName(String serviceName) throws NacosException;
383
public static void checkGroupName(String groupName) throws NacosException;
384
public static void checkDataId(String dataId) throws NacosException;
385
386
// Instance validation
387
public static void checkInstanceIsLegal(Instance instance) throws NacosException;
388
}
389
390
public class ParamUtil {
391
// Parameter parsing and validation
392
public static String parseNamespace(String namespaceId);
393
public static String parseServerAddr(String serverAddr);
394
public static boolean isDefaultGroup(String group);
395
public static boolean isBlank(String str);
396
}
397
398
public class EnvUtil {
399
// Environment detection
400
public static boolean isStandalone();
401
public static String getLocalAddress();
402
public static String getSystemProperty(String key, String defaultValue);
403
}
404
405
public class LogUtils {
406
// Logging utilities
407
public static Logger logger(Class<?> clazz);
408
public static void setLogLevel(String loggerName, String level);
409
}
410
```
411
412
## Usage Patterns
413
414
### Service Lifecycle Management
415
416
```java
417
public class NacosServiceManager {
418
private ConfigService configService;
419
private NamingService namingService;
420
private LockService lockService;
421
422
public void initialize() throws NacosException {
423
Properties props = loadConfiguration();
424
425
// Create services
426
configService = NacosFactory.createConfigService(props);
427
namingService = NacosFactory.createNamingService(props);
428
lockService = NacosFactory.createLockService(props);
429
430
// Register shutdown hook
431
Runtime.getRuntime().addShutdownHook(new Thread(this::shutdown));
432
}
433
434
public void shutdown() {
435
try {
436
if (configService != null) {
437
configService.shutDown();
438
}
439
if (namingService != null) {
440
namingService.shutDown();
441
}
442
// LockService doesn't have explicit shutdown
443
444
} catch (NacosException e) {
445
System.err.println("Error during shutdown: " + e.getMessage());
446
}
447
}
448
449
private Properties loadConfiguration() {
450
Properties props = new Properties();
451
452
// Load from system properties, environment, or config file
453
props.setProperty(PropertyKeyConst.SERVER_ADDR,
454
System.getProperty("nacos.server-addr", "localhost:8848"));
455
props.setProperty(PropertyKeyConst.NAMESPACE,
456
System.getProperty("nacos.namespace", ""));
457
458
return props;
459
}
460
}
461
```
462
463
### Error Handling Patterns
464
465
```java
466
public class NacosErrorHandler {
467
468
public void handleConfigOperations() {
469
try {
470
ConfigService configService = NacosFactory.createConfigService("localhost:8848");
471
String config = configService.getConfig("app.properties", "DEFAULT_GROUP", 5000);
472
473
} catch (NacosException e) {
474
switch (e.getErrCode()) {
475
case NacosException.CLIENT_INVALID_PARAM:
476
System.err.println("Invalid parameters: " + e.getErrMsg());
477
break;
478
case NacosException.SERVER_ERROR:
479
System.err.println("Server error: " + e.getErrMsg());
480
break;
481
case NacosException.CLIENT_DISCONNECT_FROM_SERVER:
482
System.err.println("Connection lost: " + e.getErrMsg());
483
// Implement retry logic
484
break;
485
default:
486
System.err.println("Unexpected error: " + e.getErrMsg());
487
}
488
}
489
}
490
}
491
```