Java SDK

Overview

Maven coordinates

  1. <dependency>
  2. <groupId>com.alibaba.nacos</groupId>
  3. <artifactId>nacos-client</artifactId>
  4. <version>${version}</version>
  5. </dependency>

Configuration Management

Get configuration

Description

Get configuration from Nacos when a service starts.

  1. public String getConfig(String dataId, String group, long timeoutMs) throws NacosException

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.
timeout long Length of configuration read time-out (in ms). Recommended value: 3000.

Return values

TypeDescription
stringconfiguration value

Request example

  1. try {
  2. // Initialize the configuration service, and the console automatically obtains the following parameters through the sample code.
  3. String serverAddr = "{serverAddr}";
  4. String dataId = "{dataId}";
  5. String group = "{group}";
  6. Properties properties = new Properties();
  7. properties.put("serverAddr", serverAddr);
  8. ConfigService configService = NacosFactory.createConfigService(properties);
  9. // Actively get the configuration.
  10. String content = configService.getConfig(dataId, group, 5000);
  11. System.out.println(content);
  12. } catch (NacosException e) {
  13. // TODO Auto-generated catch block
  14. e.printStackTrace();
  15. }

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.

  1. 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

TypeDescription
stringConfiguration value. This value is returned through the callback function during initialization or configuration modification.

Request example

  1. // Initialize the configuration service, and the console automatically obtains the following parameters through the sample code.
  2. String serverAddr = "{serverAddr}";
  3. String dataId = "{dataId}";
  4. String group = "{group}";
  5. Properties properties = new Properties();
  6. properties.put("serverAddr", serverAddr);
  7. ConfigService configService = NacosFactory.createConfigService(properties);
  8. String content = configService.getConfig(dataId, group, 5000);
  9. System.out.println(content);
  10. configService.addListener(dataId, group, new Listener() {
  11. @Override
  12. public void receiveConfigInfo(String configInfo) {
  13. System.out.println("receive1:" + configInfo);
  14. }
  15. @Override
  16. public Executor getExecutor() {
  17. return null;
  18. }
  19. });
  20. // 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.
  21. while (true) {
  22. try {
  23. Thread.sleep(1000);
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. }
  27. }

Delete Listening

Description

Cancel listen configuration. No more notification after cancellation.

  1. 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

  1. String serverAddr = "{serverAddr}";
  2. String dataId = "{dataId}";
  3. String group = "{group}";
  4. Properties properties = new Properties();
  5. properties.put("serverAddr", serverAddr);
  6. ConfigService configService = NacosFactory.createConfigService(properties);
  7. 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.

  1. public boolean publishConfig(String dataId, String group, String content) throws NacosException

Request parameters

NameTypeDescription
dataIdstringConfiguration ID. Naming rule is similar to package.class (com.taobao.tc.refund.log.level) is used to ensure the global uniqueness We recommend that you define class by business meaning. All characters must be in lower case. Use alphabetical letters and these four special characters (".", ":", "-", "") only. Up to 256 characters are allowed.
groupstringConfiguration group. We recommend that you use product name: module name (for example Nacos:Test) to ensure the uniqueness. Use alphabetical letters and these four special characters (".", ":", "-", "") only. Up to 128 characters are allowed.
contentstringConfiguration content. No more than 100K bytes.

Response parameters

TypeDescription
booleanIf the publishing is successful

Request example

  1. try {
  2. // Initialize the configuration service. Retrieves the following parameters in console with sample code
  3. String serverAddr = "{serverAddr}";
  4. String dataId = "{dataId}";
  5. String group = "{group}";
  6. Properties properties = new Properties();
  7. properties.put("serverAddr", serverAddr);
  8. ConfigService configService = NacosFactory.createConfigService(properties);
  9. boolean isPublishOk = configService.publishConfig(dataId, group, "content");
  10. System.out.println(isPublishOk);
  11. } catch (NacosException e) {
  12. // TODO Auto-generated catch block
  13. e.printStackTrace();
  14. }

Exceptions

In case of reading configuration timeout or network issues, ConfigException exception is thrown.

Delete configuration

Description

It deletes Nacos configurations automatically with program to reduce operation and maintenance costs with automation.

Note: If the specified configuration exists, then it deletes the configuration. If the specified configuration doesn’t exist, then it returns a successful message.

  1. public boolean removeConfig(String dataId, String group) throws NacosException

Request parameters

Parameter nameParameter typeDescription
dataIdStringConfiguration ID
groupStringConfiguration group

Response parameters

Parameter typeDescription
booleanIf the deletion is successful

Request example

  1. try {
  2. // Initialize the configuration service. Retrieves the following parameters in console with sample code
  3. String serverAddr = "{serverAddr}";
  4. String dataId = "{dataId}";
  5. String group = "{group}";
  6. Properties properties = new Properties();
  7. properties.put("serverAddr", serverAddr);
  8. ConfigService configService = NacosFactory.createConfigService(properties);
  9. boolean isRemoveOk = configService.removeConfig(dataId, group);
  10. System.out.println(isRemoveOk);
  11. } catch (NacosException e) {
  12. // TODO Auto-generated catch block
  13. e.printStackTrace();
  14. }

Exceptions

In case of reading configuration timeout or network issues, ConfigException exception is thrown.

Service Discovery SDK

Register Instance

Description

Register an instance to service.

  1. void registerInstance(String serviceName, String ip, int port) throws NacosException;
  2. void registerInstance(String serviceName, String ip, int port, String clusterName) throws NacosException;
  3. void registerInstance(String serviceName, Instance instance) throws NacosException;

Request Parameters

NameTypeDescription
serviceNameStringservice name
ipStringinstance ip
portintinstance port
clusterNameStringcluster name
instanceRefer to Java docsinstance properties

Response

void

Request Example

  1. NamingService naming = NamingFactory.createNamingService(System.getProperty("serveAddr"));
  2. naming.registerInstance("nacos.test.3", "11.11.11.11", 8888, "TEST1");
  3. Instance instance = new Instance();
  4. instance.setIp("55.55.55.55");
  5. instance.setPort(9999);
  6. instance.setHealthy(false);
  7. instance.setWeight(2.0);
  8. Map<String, String> instanceMeta = new HashMap<>();
  9. instanceMeta.put("site", "et2");
  10. instance.setMetadata(instanceMeta);
  11. Service service = new Service("nacos.test.4");
  12. service.setApp("nacos-naming");
  13. service.setHealthCheckMode("server");
  14. service.setProtectThreshold(0.8F);
  15. service.setGroup("CNCF");
  16. Map<String, String> serviceMeta = new HashMap<>();
  17. serviceMeta.put("symmetricCall", "true");
  18. service.setMetadata(serviceMeta);
  19. instance.setService(service);
  20. Cluster cluster = new Cluster();
  21. cluster.setName("TEST5");
  22. AbstractHealthChecker.Http healthChecker = new AbstractHealthChecker.Http();
  23. healthChecker.setExpectedResponseCode(400);
  24. healthChecker.setCurlHost("USer-Agent|Nacos");
  25. healthChecker.setCurlPath("/xxx.html");
  26. cluster.setHealthChecker(healthChecker);
  27. Map<String, String> clusterMeta = new HashMap<>();
  28. clusterMeta.put("xxx", "yyyy");
  29. cluster.setMetadata(clusterMeta);
  30. instance.setCluster(cluster);
  31. naming.registerInstance("nacos.test.4", instance);

Deregister Instance

Description

Remove instance from service.

  1. void deregisterInstance(String serviceName, String ip, int port) throws NacosException;
  2. void deregisterInstance(String serviceName, String ip, int port, String clusterName) throws NacosException;

Request Parameters

NameTypeDescription
serviceNameStringservice name
ipStringinstance ip
portintinstance port
clusterNameStringcluster name

Response

None

Request Example

  1. NamingService naming = NamingFactory.createNamingService(System.getProperty("serveAddr"));
  2. naming.deregisterInstance("nacos.test.3", "11.11.11.11", 8888, "DEFAULT");

Get all instances of service

Description

Get all instances of service.

  1. List<Instance> getAllInstances(String serviceName) throws NacosException;
  2. List<Instance> getAllInstances(String serviceName, List<String> clusters) throws NacosException;

Request Parameters

NameTypeDescription
serviceNameStringservice name
clustersListcluster list

Response

List instance list。

Request Example

  1. NamingService naming = NamingFactory.createNamingService(System.getProperty("serveAddr"));
  2. System.out.println(naming.getAllInstances("nacos.test.3"));

Get filtered list of instance

Description

Get healthy or unhealthy instances of service.

  1. List<Instance> selectInstances(String serviceName, boolean healthy) throws NacosException;
  2. List<Instance> selectInstances(String serviceName, List<String> clusters, boolean healthy) throws NacosException;

Request Parameters

NameTypeDescription
serviceNameStringservice name
clustersListcluster list
healthybooleanhealthy or not

Response

List instance list.

Request Example

  1. NamingService naming = NamingFactory.createNamingService(System.getProperty("serveAddr"));
  2. System.out.println(naming.selectInstances("nacos.test.3", true));

Get one healthy instance

Description

Get one healthy instance selected by load-balance strategy.

  1. Instance selectOneHealthyInstance(String serviceName) throws NacosException;
  2. Instance selectOneHealthyInstance(String serviceName, List<String> clusters) throws NacosException;

Request Parameters

NameTypeDescription
serviceNameStringservice name
clustersListcluster list

Response

Instance

Request Example

  1. NamingService naming = NamingFactory.createNamingService(System.getProperty("serveAddr"));
  2. System.out.println(naming.selectOneHealthyInstance("nacos.test.3"));

Listen Service

Description

Listen for changes of instances under a service.

  1. void subscribe(String serviceName, EventListener listener) throws NacosException;
  2. void subscribe(String serviceName, List<String> clusters, EventListener listener) throws NacosException;

Request Parameters

NameTypeDescription
serviceNameStringservice name
clustersListcluster list
listenerEventListenerevent listener

Response

void

Request Example

  1. NamingService naming = NamingFactory.createNamingService(System.getProperty("serveAddr"));
  2. naming.subscribe("nacos.test.3", event -> {
  3. if (event instanceof NamingEvent) {
  4. System.out.println(((NamingEvent) event).getServceName());
  5. System.out.println(((NamingEvent) event).getInstances());
  6. }
  7. });

Unlisten Service

Description

Cancel listening service.

  1. void unsubscribe(String serviceName, EventListener listener) throws NacosException;
  2. void unsubscribe(String serviceName, List<String> clusters, EventListener listener) throws NacosException;

Request Parameters

NameTypeDescription
serviceNameStringservice name
clustersListcluster list
listenerEventListenerevent listener

Response

void

Request Example

  1. NamingService naming = NamingFactory.createNamingService(System.getProperty("serveAddr"));
  2. naming.unsubscribe("nacos.test.3", event -> {});