Nacos client library for dynamic service discovery and configuration management in cloud native applications and microservices platforms
—
Service factory methods, utility classes, annotation support, and comprehensive exception handling. Includes capability management and extensive configuration options for all Nacos client services.
Main entry point for creating all Nacos services with unified configuration.
public class NacosFactory {
// Configuration Service creation
public static ConfigService createConfigService(Properties properties) throws NacosException;
public static ConfigService createConfigService(String serverAddr) throws NacosException;
// Naming Service creation
public static NamingService createNamingService(Properties properties) throws NacosException;
public static NamingService createNamingService(String serverAddr) throws NacosException;
// Naming Maintain Service creation (Deprecated)
public static NamingMaintainService createMaintainService(Properties properties) throws NacosException;
public static NamingMaintainService createMaintainService(String serverAddr) throws NacosException;
// Lock Service creation
public static LockService createLockService(Properties properties) throws NacosException;
public static LockService createLockService(String serverAddr) throws NacosException;
}import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.lock.LockService;
// Simple server address configuration
ConfigService configService = NacosFactory.createConfigService("localhost:8848");
NamingService namingService = NacosFactory.createNamingService("localhost:8848");
// Advanced properties configuration
Properties properties = new Properties();
properties.setProperty("serverAddr", "192.168.1.100:8848,192.168.1.101:8848");
properties.setProperty("namespace", "dev-environment");
properties.setProperty("username", "nacos");
properties.setProperty("password", "nacos123");
properties.setProperty("clusterName", "beijing");
ConfigService configSvc = NacosFactory.createConfigService(properties);
NamingService namingSvc = NacosFactory.createNamingService(properties);
LockService lockSvc = NacosFactory.createLockService(properties);Individual factories for specific service types with same configuration options.
public class ConfigFactory {
public static ConfigService createConfigService(Properties properties) throws NacosException;
public static ConfigService createConfigService(String serverAddr) throws NacosException;
}
public class NamingFactory {
public static NamingService createNamingService(Properties properties) throws NacosException;
public static NamingService createNamingService(String serverAddr) throws NacosException;
}
public class NamingMaintainFactory {
@Deprecated
public static NamingMaintainService createMaintainService(Properties properties) throws NacosException;
@Deprecated
public static NamingMaintainService createMaintainService(String serverAddr) throws NacosException;
}
public class NacosLockFactory {
public static LockService createLockService(Properties properties) throws NacosException;
public static LockService createLockService(String serverAddr) throws NacosException;
}Comprehensive configuration options for all Nacos client services.
public class PropertyKeyConst {
// Server connection
public static final String SERVER_ADDR = "serverAddr";
public static final String CONTEXT_PATH = "contextPath";
public static final String CLUSTER_NAME = "clusterName";
public static final String ENCODE = "encode";
public static final String NAMESPACE = "namespace";
// Authentication
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String ACCESS_KEY = "accessKey";
public static final String SECRET_KEY = "secretKey";
// SSL/TLS
public static final String IS_USE_CLOUD_NAMESPACE_PARSING = "isUseCloudNamespaceParsing";
public static final String IS_USE_ENDPOINT_PARSING_RULE = "isUseEndpointParsingRule";
// Performance tuning
public static final String NAMING_LOAD_CACHE_AT_START = "namingLoadCacheAtStart";
public static final String NAMING_CLIENT_BEAT_THREAD_COUNT = "namingClientBeatThreadCount";
public static final String NAMING_POLLING_THREAD_COUNT = "namingPollingThreadCount";
public static final String NAMING_REQUEST_DOMAIN_RETRY_COUNT = "namingRequestDomainMaxRetryCount";
public static final String NAMING_PUSH_EMPTY_PROTECTION = "namingPushEmptyProtection";
// Configuration specific
public static final String CONFIG_LONG_POLL_TIMEOUT = "configLongPollTimeout";
public static final String CONFIG_RETRY_TIME = "configRetryTime";
public static final String MAX_RETRY = "maxRetry";
public static final String ENABLE_REMOTE_SYNC_CONFIG = "enableRemoteSyncConfig";
// Connection pooling
public static final String CONN_POOL_SIZE = "connPoolSize";
public static final String CONN_POOL_TIMEOUT = "connPoolTimeout";
public static final String CONN_POOL_ALIVE = "connPoolAlive";
}// High availability configuration
Properties props = new Properties();
props.setProperty(PropertyKeyConst.SERVER_ADDR, "nacos1:8848,nacos2:8848,nacos3:8848");
props.setProperty(PropertyKeyConst.NAMESPACE, "production");
props.setProperty(PropertyKeyConst.CLUSTER_NAME, "us-west");
// Authentication configuration
props.setProperty(PropertyKeyConst.USERNAME, "admin");
props.setProperty(PropertyKeyConst.PASSWORD, "admin123");
// Performance tuning
props.setProperty(PropertyKeyConst.NAMING_CLIENT_BEAT_THREAD_COUNT, "5");
props.setProperty(PropertyKeyConst.NAMING_POLLING_THREAD_COUNT, "10");
props.setProperty(PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT, "30000");
// Connection pooling
props.setProperty(PropertyKeyConst.CONN_POOL_SIZE, "20");
props.setProperty(PropertyKeyConst.CONN_POOL_TIMEOUT, "3000");
ConfigService configService = NacosFactory.createConfigService(props);System-level property keys for global configuration.
public class SystemPropertyKeyConst {
// JVM system properties
public static final String IS_USE_CLOUD_NAMESPACE_PARSING = "IS_USE_CLOUD_NAMESPACE_PARSING";
public static final String IS_USE_ENDPOINT_PARSING_RULE = "IS_USE_ENDPOINT_PARSING_RULE";
public static final String NAMING_SERVER_PORT = "NAMING_SERVER_PORT";
public static final String CONFIG_SERVER_PORT = "CONFIG_SERVER_PORT";
// Environment specific
public static final String JM_SNAPSHOT_PATH = "JM.SNAPSHOT.PATH";
public static final String JM_LOG_PATH = "JM.LOG.PATH";
}Comprehensive exception handling for all Nacos operations.
// Main checked exception
public class NacosException extends Exception {
// Error codes
public static final int CLIENT_INVALID_PARAM = 400;
public static final int CLIENT_OVER_THRESHOLD = 503;
public static final int CLIENT_DISCONNECT_FROM_SERVER = -1001;
public static final int SERVER_ERROR = 500;
public static final int BAD_GATEWAY = 502;
public static final int OVER_THRESHOLD = 503;
public static final int RESOURCE_NOT_FOUND = 404;
public static final int CLIENT_ERROR = -1000;
public static final int CONFLICT = 409;
public static final int ACCESS_DENIED = 403;
public static final int INVALID_SERVER_STATUS = -1002;
public NacosException(int errCode, String errMsg);
public NacosException(int errCode, String errMsg, Throwable cause);
public int getErrCode();
public String getErrMsg();
}
// Runtime exceptions
public class NacosRuntimeException extends RuntimeException {
public NacosRuntimeException(String message);
public NacosRuntimeException(String message, Throwable cause);
}
public class NacosLoadException extends NacosRuntimeException {
public NacosLoadException(String message);
public NacosLoadException(String message, Throwable cause);
}
public class NacosSerializationException extends NacosRuntimeException {
public NacosSerializationException(String message);
public NacosSerializationException(String message, Throwable cause);
}
public class NacosDeserializationException extends NacosRuntimeException {
public NacosDeserializationException(String message);
public NacosDeserializationException(String message, Throwable cause);
}
// API-specific exception
public class NacosApiException extends NacosException {
public NacosApiException(int errCode, String errMsg);
public NacosApiException(int errCode, String errMsg, Throwable cause);
}Standard constants used across all Nacos services.
public class Constants {
// Default values
public static final String DEFAULT_GROUP = "DEFAULT_GROUP";
public static final String DEFAULT_NAMESPACE_ID = "";
public static final String CLIENT_VERSION = "3.0.2";
// Separators and patterns
public static final String WORD_SEPARATOR = "-";
public static final String LINE_SEPARATOR = Character.toString((char) 1);
public static final String BASE_PATH = "/nacos";
public static final String ANY_PATTERN = "*";
// Timeout values
public static final int DEFAULT_TIMEOUT = 3000;
public static final long DEFAULT_HEART_BEAT_TIMEOUT = 15000L;
public static final long DEFAULT_IP_DELETE_TIMEOUT = 30000L;
// Encoding
public static final String ENCODE_UTF8 = "UTF-8";
public static final String ENCODE_GBK = "GBK";
// HTTP headers
public static final String CLIENT_VERSION_HEADER = "Client-Version";
public static final String USER_AGENT_HEADER = "User-Agent";
}
public class ResponseCode {
public static final int SUCCESS = 200;
public static final int FAIL = 500;
public static final int UNAUTHORIZED = 401;
public static final int FORBIDDEN = 403;
public static final int NOT_FOUND = 404;
public static final int INTERNAL_ERROR = 500;
public static final int BAD_GATEWAY = 502;
public static final int SERVICE_UNAVAILABLE = 503;
}
public enum NodeState {
UP("UP"),
DOWN("DOWN"),
STARTING("STARTING"),
SUSPECT("SUSPECT");
private final String state;
NodeState(String state) {
this.state = state;
}
public String getState();
}Comprehensive annotation support for dependency injection and configuration binding.
// Dependency injection annotations
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NacosInjected {
// Properties for service creation
NacosProperties[] properties() default {};
}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NacosApi {
String value() default "";
}
@Repeatable(NacosProperties.List.class)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NacosProperties {
String prefix() default "";
String[] value() default {};
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface List {
NacosProperties[] value();
}
}Client and server capability management for feature negotiation.
public class ClientAbilities {
private Map<AbilityKey, Boolean> abilities;
public ClientAbilities();
public boolean isSupported(AbilityKey abilityKey);
public void setSupported(AbilityKey abilityKey, boolean supported);
public Map<AbilityKey, Boolean> getAbilities();
}
public class ServerAbilities {
private Map<AbilityKey, Boolean> abilities;
public ServerAbilities();
public boolean isSupported(AbilityKey abilityKey);
public void setSupported(AbilityKey abilityKey, boolean supported);
public Map<AbilityKey, Boolean> getAbilities();
}
// Capability identifiers
public enum AbilityKey {
SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC("supportPersistentInstanceByGrpc"),
SERVER_SUPPORT_REMOTE_CONNECTION("supportRemoteConnection"),
SERVER_SUPPORT_CONFIG_FUZZY_WATCH("supportConfigFuzzyWatch"),
SERVER_SUPPORT_NAMING_FUZZY_WATCH("supportNamingFuzzyWatch"),
SDK_CLIENT_SUPPORT_FUZZY_WATCH("supportFuzzyWatch");
private final String name;
AbilityKey(String name) {
this.name = name;
}
public String getName();
}
// Capability states
public enum AbilityStatus {
SUPPORTED("supported"),
NOT_SUPPORTED("not_supported"),
UNKNOWN("unknown");
private final String status;
AbilityStatus(String status) {
this.status = status;
}
public String getStatus();
}Common utility functions for validation, parameter handling, and environment setup.
public class ValidatorUtils {
// Parameter validation
public static void checkInitParam(Properties properties) throws NacosException;
public static void checkServiceName(String serviceName) throws NacosException;
public static void checkGroupName(String groupName) throws NacosException;
public static void checkDataId(String dataId) throws NacosException;
// Instance validation
public static void checkInstanceIsLegal(Instance instance) throws NacosException;
}
public class ParamUtil {
// Parameter parsing and validation
public static String parseNamespace(String namespaceId);
public static String parseServerAddr(String serverAddr);
public static boolean isDefaultGroup(String group);
public static boolean isBlank(String str);
}
public class EnvUtil {
// Environment detection
public static boolean isStandalone();
public static String getLocalAddress();
public static String getSystemProperty(String key, String defaultValue);
}
public class LogUtils {
// Logging utilities
public static Logger logger(Class<?> clazz);
public static void setLogLevel(String loggerName, String level);
}public class NacosServiceManager {
private ConfigService configService;
private NamingService namingService;
private LockService lockService;
public void initialize() throws NacosException {
Properties props = loadConfiguration();
// Create services
configService = NacosFactory.createConfigService(props);
namingService = NacosFactory.createNamingService(props);
lockService = NacosFactory.createLockService(props);
// Register shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread(this::shutdown));
}
public void shutdown() {
try {
if (configService != null) {
configService.shutDown();
}
if (namingService != null) {
namingService.shutDown();
}
// LockService doesn't have explicit shutdown
} catch (NacosException e) {
System.err.println("Error during shutdown: " + e.getMessage());
}
}
private Properties loadConfiguration() {
Properties props = new Properties();
// Load from system properties, environment, or config file
props.setProperty(PropertyKeyConst.SERVER_ADDR,
System.getProperty("nacos.server-addr", "localhost:8848"));
props.setProperty(PropertyKeyConst.NAMESPACE,
System.getProperty("nacos.namespace", ""));
return props;
}
}public class NacosErrorHandler {
public void handleConfigOperations() {
try {
ConfigService configService = NacosFactory.createConfigService("localhost:8848");
String config = configService.getConfig("app.properties", "DEFAULT_GROUP", 5000);
} catch (NacosException e) {
switch (e.getErrCode()) {
case NacosException.CLIENT_INVALID_PARAM:
System.err.println("Invalid parameters: " + e.getErrMsg());
break;
case NacosException.SERVER_ERROR:
System.err.println("Server error: " + e.getErrMsg());
break;
case NacosException.CLIENT_DISCONNECT_FROM_SERVER:
System.err.println("Connection lost: " + e.getErrMsg());
// Implement retry logic
break;
default:
System.err.println("Unexpected error: " + e.getErrMsg());
}
}
}
}Install with Tessl CLI
npx tessl i tessl/maven-com-alibaba-nacos--nacos-client