Nacos API package providing interfaces and common classes for dynamic service discovery, configuration management, and service management in cloud native applications and microservices
—
Core factory classes and property constants for creating and configuring Nacos services. These are essential components for initializing any Nacos functionality and provide the foundation for all other operations.
Central factory class for creating all Nacos service instances. This is the primary entry point for obtaining ConfigService, NamingService, and LockService instances.
/**
* Main factory class for creating Nacos service instances
*/
class NacosFactory {
/**
* Create ConfigService with properties configuration
* @param properties Configuration properties containing server address and other settings
* @return ConfigService instance for configuration management
* @throws NacosException If service creation fails
*/
static ConfigService createConfigService(Properties properties) throws NacosException;
/**
* Create ConfigService with simple server address
* @param serverAddr Nacos server address (e.g., "127.0.0.1:8848")
* @return ConfigService instance for configuration management
* @throws NacosException If service creation fails
*/
static ConfigService createConfigService(String serverAddr) throws NacosException;
/**
* Create NamingService with server address
* @param serverAddr Nacos server address (e.g., "127.0.0.1:8848")
* @return NamingService instance for service discovery
* @throws NacosException If service creation fails
*/
static NamingService createNamingService(String serverAddr) throws NacosException;
/**
* Create NamingService with properties configuration
* @param properties Configuration properties containing server address and other settings
* @return NamingService instance for service discovery
* @throws NacosException If service creation fails
*/
static NamingService createNamingService(Properties properties) throws NacosException;
/**
* Create NamingMaintainService with server address (Deprecated)
* @param serverAddr Nacos server address
* @return NamingMaintainService instance for service maintenance
* @throws NacosException If service creation fails
* @deprecated Use NamingService instead
*/
@Deprecated
static NamingMaintainService createMaintainService(String serverAddr) throws NacosException;
/**
* Create NamingMaintainService with properties (Deprecated)
* @param properties Configuration properties
* @return NamingMaintainService instance for service maintenance
* @throws NacosException If service creation fails
* @deprecated Use NamingService instead
*/
@Deprecated
static NamingMaintainService createMaintainService(Properties properties) throws NacosException;
/**
* Create LockService with properties configuration
* @param properties Configuration properties containing server address and other settings
* @return LockService instance for distributed locking
* @throws NacosException If service creation fails
*/
static LockService createLockService(Properties properties) throws NacosException;
}Usage Examples:
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import java.util.Properties;
// Create services with simple server address
ConfigService configService = NacosFactory.createConfigService("127.0.0.1:8848");
NamingService namingService = NacosFactory.createNamingService("127.0.0.1:8848");
// Create services with detailed properties
Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848");
properties.setProperty(PropertyKeyConst.NAMESPACE, "dev");
properties.setProperty(PropertyKeyConst.USERNAME, "nacos");
properties.setProperty(PropertyKeyConst.PASSWORD, "nacos");
ConfigService configServiceWithAuth = NacosFactory.createConfigService(properties);
NamingService namingServiceWithAuth = NacosFactory.createNamingService(properties);
LockService lockService = NacosFactory.createLockService(properties);
// Multiple server addresses for high availability
properties.setProperty(PropertyKeyConst.SERVER_ADDR, "192.168.1.1:8848,192.168.1.2:8848,192.168.1.3:8848");
ConfigService haConfigService = NacosFactory.createConfigService(properties);Constants for property keys used in Nacos configuration. These constants ensure consistent configuration across different Nacos services.
/**
* Constants for property keys used in Nacos configuration
*/
class PropertyKeyConst {
/** Nacos server address, supports multiple addresses separated by comma */
static final String SERVER_ADDR = "serverAddr";
/** Namespace ID for multi-tenancy support */
static final String NAMESPACE = "namespace";
/** Username for authentication */
static final String USERNAME = "username";
/** Password for authentication */
static final String PASSWORD = "password";
/** Access key for cloud authentication */
static final String ACCESS_KEY = "accessKey";
/** Secret key for cloud authentication */
static final String SECRET_KEY = "secretKey";
/** Context path for Nacos server */
static final String CONTEXT_PATH = "contextPath";
/** Cluster name for service registration */
static final String CLUSTER_NAME = "clusterName";
/** Character encoding for configuration content */
static final String ENCODE = "encode";
/** Timeout for configuration long polling in milliseconds */
static final String CONFIG_LONG_POLL_TIMEOUT = "configLongPollTimeout";
/** Retry interval for configuration operations in milliseconds */
static final String CONFIG_RETRY_TIME = "configRetryTime";
/** Maximum retry attempts */
static final String MAX_RETRY = "maxRetry";
/** Request timeout for configuration operations in milliseconds */
static final String CONFIG_REQUEST_TIMEOUT = "configRequestTimeout";
/** RAM role name for cloud authentication */
static final String RAM_ROLE_NAME = "ramRoleName";
/** Enable remote sync configuration */
static final String ENABLE_REMOTE_SYNC_CONFIG = "enableRemoteSyncConfig";
/** Endpoint for cloud mode */
static final String ENDPOINT = "endpoint";
/** Port offset for endpoint */
static final String ENDPOINT_PORT = "endpointPort";
/** Query parameters for endpoint */
static final String ENDPOINT_QUERY_PARAMS = "endpointQueryParams";
/** Context path for endpoint */
static final String ENDPOINT_CONTEXT_PATH = "endpointContextPath";
/** Cluster name for endpoint */
static final String ENDPOINT_CLUSTER_NAME = "endpointClusterName";
/** Refresh interval for endpoint in seconds */
static final String ENDPOINT_REFRESH_INTERVAL_SECONDS = "endpointRefreshIntervalSeconds";
/** Is use endpoint parsing rule */
static final String IS_USE_ENDPOINT_PARSING_RULE = "isUseEndpointParsingRule";
/** Is use cloud namespace parsing */
static final String IS_USE_CLOUD_NAMESPACE_PARSING = "isUseCloudNamespaceParsing";
/** Naming push empty protection */
static final String NAMING_PUSH_EMPTY_PROTECTION = "namingPushEmptyProtection";
/** Naming load cache at start */
static final String NAMING_LOAD_CACHE_AT_START = "namingLoadCacheAtStart";
/** Naming client beat thread count */
static final String NAMING_CLIENT_BEAT_THREAD_COUNT = "namingClientBeatThreadCount";
/** Naming polling thread count */
static final String NAMING_POLLING_THREAD_COUNT = "namingPollingThreadCount";
/** Naming polling max thread count */
static final String NAMING_POLLING_MAX_THREAD_COUNT = "namingPollingMaxThreadCount";
/** Naming cache registry directory */
static final String NAMING_CACHE_REGISTRY_DIR = "namingCacheRegistryDir";
/** Naming request domain retry count */
static final String NAMING_REQUEST_DOMAIN_RETRY_COUNT = "namingRequestDomainMaxRetryCount";
/** Naming async query subscribe service */
static final String NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE = "namingAsyncQuerySubscribeService";
/** Client worker thread count */
static final String CLIENT_WORKER_THREAD_COUNT = "clientWorkerThreadCount";
/** Client worker max thread count */
static final String CLIENT_WORKER_MAX_THREAD_COUNT = "clientWorkerMaxThreadCount";
/** Redo delay time */
static final String REDO_DELAY_TIME = "redoDelayTime";
/** Redo delay thread count */
static final String REDO_DELAY_THREAD_COUNT = "redoDelayThreadCount";
/** Signature region ID */
static final String SIGNATURE_REGION_ID = "signatureRegionId";
/** Log all properties */
static final String LOG_ALL_PROPERTIES = "logAllProperties";
/** Is use RAM info parsing */
static final String IS_USE_RAM_INFO_PARSING = "isUseRamInfoParsing";
/** Enable client metrics */
static final String ENABLE_CLIENT_METRICS = "enableClientMetrics";
/** Server name (deprecated) */
@Deprecated
static final String SERVER_NAME = "serverName";
/** Is adapt cluster name usage (deprecated) */
@Deprecated
static final String IS_ADAPT_CLUSTER_NAME_USAGE = "isAdaptClusterNameUsage";
/** System environment constants */
static class SystemEnv {
static final String ALIBABA_ALIWARE_ENDPOINT_PORT = "ALIBABA_ALIWARE_ENDPOINT_PORT";
static final String ALIBABA_ALIWARE_ENDPOINT_CONTEXT_PATH = "ALIBABA_ALIWARE_ENDPOINT_CONTEXT_PATH";
static final String ALIBABA_ALIWARE_NAMESPACE = "ALIBABA_ALIWARE_NAMESPACE";
static final String ALIBABA_ALIWARE_ENDPOINT_URL = "ALIBABA_ALIWARE_ENDPOINT_URL";
}
}Usage Examples:
import com.alibaba.nacos.api.PropertyKeyConst;
import java.util.Properties;
// Basic configuration
Properties props = new Properties();
props.setProperty(PropertyKeyConst.SERVER_ADDR, "localhost:8848");
props.setProperty(PropertyKeyConst.NAMESPACE, "production");
// Authentication configuration
props.setProperty(PropertyKeyConst.USERNAME, "admin");
props.setProperty(PropertyKeyConst.PASSWORD, "secret");
// Cloud configuration with access keys
props.setProperty(PropertyKeyConst.ACCESS_KEY, "your-access-key");
props.setProperty(PropertyKeyConst.SECRET_KEY, "your-secret-key");
props.setProperty(PropertyKeyConst.ENDPOINT, "nacos.cloud.example.com");
// Performance tuning
props.setProperty(PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT, "60000"); // 60 seconds
props.setProperty(PropertyKeyConst.CONFIG_RETRY_TIME, "3000"); // 3 seconds
props.setProperty(PropertyKeyConst.MAX_RETRY, "5");
// Naming service configuration
props.setProperty(PropertyKeyConst.CLUSTER_NAME, "default");
props.setProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START, "true");
props.setProperty(PropertyKeyConst.NAMING_CLIENT_BEAT_THREAD_COUNT, "2");
// Additional configuration options
props.setProperty(PropertyKeyConst.ENABLE_REMOTE_SYNC_CONFIG, "true");
props.setProperty(PropertyKeyConst.CONFIG_REQUEST_TIMEOUT, "10000"); // 10 secondsSystem property keys for JVM parameters that control Nacos behavior at the system level.
/**
* System property keys for JVM parameters
*/
interface SystemPropertyKeyConst {
/** Naming server port for service exposure */
String NAMING_SERVER_PORT = "nacos.naming.exposed.port";
/** Enable cloud namespace parsing */
String IS_USE_CLOUD_NAMESPACE_PARSING = "nacos.use.cloud.namespace.parsing";
/** ANS (Application Naming Service) namespace */
String ANS_NAMESPACE = "ans.namespace";
/** Enable endpoint parsing rule */
String IS_USE_ENDPOINT_PARSING_RULE = "nacos.use.endpoint.parsing.rule";
/** Enable RAM (Resource Access Management) info parsing */
String IS_USE_RAM_INFO_PARSING = "nacos.use.ram.info.parsing";
}Usage Examples:
// Set system properties before creating Nacos services
System.setProperty(SystemPropertyKeyConst.NAMING_SERVER_PORT, "8080");
System.setProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, "true");
System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "true");
// Or set via JVM arguments:
// -Dnacos.naming.exposed.port=8080
// -Dnacos.use.cloud.namespace.parsing=true
// -Dnacos.use.endpoint.parsing.rule=trueCommon patterns for validating and setting up Nacos properties:
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.utils.StringUtils;
public class NacosConfigValidator {
public static Properties validateAndSetup(Properties properties) {
Properties validatedProps = new Properties(properties);
// Ensure server address is provided
String serverAddr = validatedProps.getProperty(PropertyKeyConst.SERVER_ADDR);
if (StringUtils.isBlank(serverAddr)) {
throw new IllegalArgumentException("serverAddr must be provided");
}
// Set default namespace if not provided
if (StringUtils.isBlank(validatedProps.getProperty(PropertyKeyConst.NAMESPACE))) {
validatedProps.setProperty(PropertyKeyConst.NAMESPACE, "public");
}
// Set default encoding if not provided
if (StringUtils.isBlank(validatedProps.getProperty(PropertyKeyConst.ENCODE))) {
validatedProps.setProperty(PropertyKeyConst.ENCODE, "UTF-8");
}
// Set default timeouts if not provided
if (StringUtils.isBlank(validatedProps.getProperty(PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT))) {
validatedProps.setProperty(PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT, "30000");
}
if (StringUtils.isBlank(validatedProps.getProperty(PropertyKeyConst.MAX_RETRY))) {
validatedProps.setProperty(PropertyKeyConst.MAX_RETRY, "3");
}
return validatedProps;
}
}
// Usage
Properties props = new Properties();
props.setProperty(PropertyKeyConst.SERVER_ADDR, "localhost:8848");
Properties validatedProps = NacosConfigValidator.validateAndSetup(props);
ConfigService configService = NacosFactory.createConfigService(validatedProps);Common error scenarios and handling patterns when using factory methods:
import com.alibaba.nacos.api.exception.NacosException;
try {
Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.SERVER_ADDR, "localhost:8848");
ConfigService configService = NacosFactory.createConfigService(properties);
NamingService namingService = NacosFactory.createNamingService(properties);
} catch (NacosException e) {
switch (e.getErrCode()) {
case NacosException.CLIENT_INVALID_PARAM:
// Handle invalid parameters (e.g., missing server address)
logger.error("Invalid configuration parameters", e);
break;
case NacosException.CLIENT_DISCONNECT:
// Handle connection issues
logger.error("Failed to connect to Nacos server", e);
break;
case NacosException.SERVER_ERROR:
// Handle server-side errors
logger.error("Nacos server error", e);
break;
default:
// Handle other errors
logger.error("Unexpected error creating Nacos service", e);
break;
}
}Install with Tessl CLI
npx tessl i tessl/maven-com-alibaba-nacos--nacos-api