Java SDK
Description
Get configuration from Nacos when a service starts.
Request parameters
Return values
Type | Description |
---|---|
string | configuration value |
Request example
try {
// Initialize the configuration service, and the console automatically obtains the following parameters through the sample code.
String serverAddr = "{serverAddr}";
String group = "{group}";
Properties properties = new Properties();
properties.put("serverAddr", serverAddr);
ConfigService configService = NacosFactory.createConfigService(properties);
// Actively get the configuration.
String content = configService.getConfig(dataId, group, 5000);
System.out.println(content);
} catch (NacosException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Exception specification
A ConfigException is thrown in case of a configuration read time-out or a network error.
Listen configuration
Description
Use dynamic configuration listening API to enable Nacos to send configuration change notifications.
public void addListener(String dataId, ConfigChangeListenerAdapter listener)
Request parameters
Name | Type | Description |
dataId | string | Configuration ID. Use a naming rule similar to package.class (for example, com.taobao.tc.refund.log.level) to ensure global uniqueness. It is recommended to indicate business meaning of the configuration in the "class" section. Use lower case for all characters. Use alphabetical letters and these four special characters (".", ":", "-", "") only. Up to 256 characters are allowed. |
group | string | Configuration group. To ensure uniqueness, format such as product name: module name (for example, Nacos:Test) is preferred. Use alphabetical letters and these four special characters (".", ":", "-", "") only. Up to 128 characters are allowed. |
listener | Config Change Listener | Listener. Configuration changes go into the callback function of the listener. |
Return values
Type | Description |
---|---|
string | Configuration value. This value is returned through the callback function during initialization or configuration modification. |
Request example
// Initialize the configuration service, and the console automatically obtains the following parameters through the sample code.
String serverAddr = "{serverAddr}";
String dataId = "{dataId}";
String group = "{group}";
Properties properties = new Properties();
properties.put("serverAddr", serverAddr);
ConfigService configService = NacosFactory.createConfigService(properties);
String content = configService.getConfig(dataId, group, 5000);
System.out.println(content);
configService.addListener(dataId, group, new Listener() {
@Override
public void receiveConfigInfo(String configInfo) {
System.out.println("receive1:" + configInfo);
}
@Override
public Executor getExecutor() {
return null;
}
});
// Keep the main thread alive throughout the test, because the configuration subscription runs in a daemon thread, which exits once the main thread exits. The following code is not required in a real environment.
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Delete Listening
Description
Cancel listen configuration. No more notification after cancellation.
public void removeListener(String dataId, String group, Listener listener)
Request parameters
Name | Type | Description |
dataId | string | Configuration ID. Use a naming rule similar to package.class (for example, com.taobao.tc.refund.log.level) to ensure global uniqueness. It is recommended to indicate business meaning of the configuration in the "class" section. Use lower case for all characters. Use alphabetical letters and these four special characters (".", ":", "-", "_") only. Up to 256 characters are allowed. |
group | string | Configuration group |
listener | ConfigChangeListenerAdapter | Listener. Configuration changes go into the callback function of the listener. |
Request example
String serverAddr = "{serverAddr}";
String group = "{group}";
Properties properties = new Properties();
properties.put("serverAddr", serverAddr);
ConfigService configService = NacosFactory.createConfigService(properties);
configService.removeListener(dataId, group, yourListener);
Publish configuration
Description
Publish Nacos configurations automatically to reduce the operation and maintenance cost.
Note: It uses the same publishing interface to create or modify a configuration. If the specified configuration doesn’t exist, it will create a configuration. If the specified configuration exists, it will update the configuration.
public boolean publishConfig(String dataId, String group, String content) throws NacosException
Request parameters
Response parameters
Type | Description |
---|---|
boolean | If the publishing is successful |
Request example
Exceptions
In case of reading configuration timeout or network issues, ConfigException exception is thrown.
Description
Note: If the specified configuration exists, then it deletes the configuration. If the specified configuration doesn’t exist, then it returns a successful message.
public boolean removeConfig(String dataId, String group) throws NacosException
Request parameters
Parameter name | Parameter type | Description |
---|---|---|
dataId | String | Configuration ID |
group | String | Configuration group |
Response parameters
Parameter type | Description |
---|---|
boolean | If the deletion is successful |
Request example
try {
// Initialize the configuration service. Retrieves the following parameters in console with sample code
String serverAddr = "{serverAddr}";
String dataId = "{dataId}";
String group = "{group}";
Properties properties = new Properties();
properties.put("serverAddr", serverAddr);
ConfigService configService = NacosFactory.createConfigService(properties);
boolean isRemoveOk = configService.removeConfig(dataId, group);
System.out.println(isRemoveOk);
} catch (NacosException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Exceptions
In case of reading configuration timeout or network issues, ConfigException exception is thrown.
Register Instance
Description
Register an instance to service.
void registerInstance(String serviceName, String ip, int port) throws NacosException;
void registerInstance(String serviceName, String ip, int port, String clusterName) throws NacosException;
void registerInstance(String serviceName, Instance instance) throws NacosException;
Request Parameters
Name | Type | Description |
---|---|---|
serviceName | String | service name |
ip | String | instance ip |
port | int | instance port |
clusterName | String | cluster name |
instance | Refer to Java docs | instance properties |
Response
void
Request Example
NamingService naming = NamingFactory.createNamingService(System.getProperty("serveAddr"));
naming.registerInstance("nacos.test.3", "11.11.11.11", 8888, "TEST1");
Instance instance = new Instance();
instance.setIp("55.55.55.55");
instance.setPort(9999);
instance.setHealthy(false);
instance.setWeight(2.0);
Map<String, String> instanceMeta = new HashMap<>();
instanceMeta.put("site", "et2");
instance.setMetadata(instanceMeta);
Service service = new Service("nacos.test.4");
service.setApp("nacos-naming");
service.setHealthCheckMode("server");
service.setProtectThreshold(0.8F);
service.setGroup("CNCF");
Map<String, String> serviceMeta = new HashMap<>();
service.setMetadata(serviceMeta);
instance.setService(service);
Cluster cluster = new Cluster();
cluster.setName("TEST5");
AbstractHealthChecker.Http healthChecker = new AbstractHealthChecker.Http();
healthChecker.setExpectedResponseCode(400);
healthChecker.setCurlHost("USer-Agent|Nacos");
healthChecker.setCurlPath("/xxx.html");
cluster.setHealthChecker(healthChecker);
Map<String, String> clusterMeta = new HashMap<>();
clusterMeta.put("xxx", "yyyy");
cluster.setMetadata(clusterMeta);
instance.setCluster(cluster);
naming.registerInstance("nacos.test.4", instance);
Deregister Instance
Description
Remove instance from service.
void deregisterInstance(String serviceName, String ip, int port) throws NacosException;
void deregisterInstance(String serviceName, String ip, int port, String clusterName) throws NacosException;
Request Parameters
Response
None
Request Example
NamingService naming = NamingFactory.createNamingService(System.getProperty("serveAddr"));
naming.deregisterInstance("nacos.test.3", "11.11.11.11", 8888, "DEFAULT");
Get all instances of service
Description
Get all instances of service.
List<Instance> getAllInstances(String serviceName) throws NacosException;
List<Instance> getAllInstances(String serviceName, List<String> clusters) throws NacosException;
Request Parameters
Name | Type | Description |
---|---|---|
serviceName | String | service name |
clusters | List | cluster list |
Response
Request Example
Description
Get healthy or unhealthy instances of service.
List<Instance> selectInstances(String serviceName, boolean healthy) throws NacosException;
List<Instance> selectInstances(String serviceName, List<String> clusters, boolean healthy) throws NacosException;
Request Parameters
Name | Type | Description |
---|---|---|
serviceName | String | service name |
clusters | List | cluster list |
healthy | boolean | healthy or not |
Response
List
Request Example
NamingService naming = NamingFactory.createNamingService(System.getProperty("serveAddr"));
System.out.println(naming.selectInstances("nacos.test.3", true));
Get one healthy instance
Description
Get one healthy instance selected by load-balance strategy.
Instance selectOneHealthyInstance(String serviceName) throws NacosException;
Instance selectOneHealthyInstance(String serviceName, List<String> clusters) throws NacosException;
Request Parameters
Name | Type | Description |
---|---|---|
serviceName | String | service name |
clusters | List | cluster list |
Response
Instance
Request Example
NamingService naming = NamingFactory.createNamingService(System.getProperty("serveAddr"));
System.out.println(naming.selectOneHealthyInstance("nacos.test.3"));
Listen Service
Description
Listen for changes of instances under a service.
void subscribe(String serviceName, EventListener listener) throws NacosException;
void subscribe(String serviceName, List<String> clusters, EventListener listener) throws NacosException;
Request Parameters
Name | Type | Description |
---|---|---|
serviceName | String | service name |
clusters | List | cluster list |
listener | EventListener | event listener |
Response
void
Request Example
NamingService naming = NamingFactory.createNamingService(System.getProperty("serveAddr"));
naming.subscribe("nacos.test.3", event -> {
if (event instanceof NamingEvent) {
System.out.println(((NamingEvent) event).getServceName());
System.out.println(((NamingEvent) event).getInstances());
}
});
Unlisten Service
Description
Cancel listening service.
void unsubscribe(String serviceName, EventListener listener) throws NacosException;