Skip to main content
Version: 2.2.8.RELEASE

Advanced Guide

This chapter shows the advanced features and advanced usage of spring-cloud-starter-alibaba-nacos-config and spring-cloud-starter-alibaba-nacos-discovery.

Nacos Configuration Center Advanced Guide

profile granularity configration

spring-cloud-starter-alibaba-nacos-config When loading the service configuration:

Not only is the base configuration prefixed with dataId ${spring.application.name}.${file-extension:properties} loaded,

The base configuration with dataId of ${spring.application.name}-${profile}.${file-extension:properties} is also loaded.

In daily development, if you encounter different configurations in multiple environments, you can select different configurations through the ${spring.Profiles.active} configuration item provided by spring.

spring.profiles.active=develop

Note:

spring.profiles.active=develop

A new dataId on nacos is: basic configuration of nacos-config-develop.yaml, as shown below:

Data ID: nacos-config-develop.yaml
Group: DEFAULT_GROUP
confiuration style: YAML
configuration content: current.env: develop-env

The code to start the Spring Boot application test is as follows:

@SpringBootApplication
public class ProviderApplication {

public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(ProviderApplication.class, args);
while(true) {
String userName = applicationContext.getEnvironment().getProperty("user.name");
String userAge = applicationContext.getEnvironment().getProperty("user.age");
// Gets the currently deployed environment
String currentEnv = applicationContext.getEnvironment().getProperty("current.env");
System.err.println("in "+currentEnv+" enviroment; "+"user name :" + userName + "; age: " + userAge);
TimeUnit.SECONDS.sleep(1);
}
}
}

The console output is as follows:

in develop-env enviroment; user name :nacos-config-yaml-update; age: 68
The 2018-11-02 15:34:25. 33014-013 the INFO/Thread - 11 ConfigServletWebServerApplicationContext: Closing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6f1c29b7: startup date [Fri Nov 02 15:33:57 CST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@63355449

If you need to switch to production, just change the ${spring.profiles.active} parameter configuration. As follows:

spring.profiles.active=product

At the same time, basic configuration of corresponding dataId needs to be added to Nacos in the production environment. For example, nacos in the generation environment adds a configuration with dataId of: nacos-config-product.yaml:

Data ID: nacos-config-develop.yaml
Group: DEFAULT_GROUP
confiuration style: YAML
configuration content: current.env: develop-env

Start the test program, and the output is as follows:

in product-env enviroment; user name :nacos-config-yaml-update; age: 68
The 2018-11-02 15:42:14. 33024-628 the INFO/Thread - 11 ConfigServletWebServerApplicationContext: Closing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6aa8e115: startup date [Fri Nov 02 15:42:03 CST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@19bb07ed

Note:

In this case, we wrote `spring.profilename.active=profilename to the configuration file, but in real project implementation, the value of this variable will vary depending on the environment. It is common practice at this point to specify its configuration via the spring.profes.active=profile parameter to achieve flexible switching between environments.

User-defined namespace configurations

Inside Nacos there is the concept of Namespace:

For tenant granularity configuration isolation. The same Group or Data ID can be configured in different namespaces. A common scenario of Namespace is to separate and isolate configurations of different environments. For example, isolation of resources (such as configurations and services) between the development and test environments and production environments. without explicitly specify ${spring.cloud.nacos.config.namespace} configuration, the default is used on Public nacos this namespace. If you want to use a custom defined namespace, you can use the following configuration:

spring.cloud.nacos.config.namespace=YOUR_NAMESPACE_ID

NOTE:

This configuration must be placed in the bootstrap.properties file. Besides spring.cloud.nacos.config.namespace. The value of the namespace is namespace corresponding id, id value can be > nacos console access. Do not select any other namespae when adding the configuration. Otherwise, the correct configuration will not be read.

User-defined Group configuration

Without explicitly specify ${spring.cloud.nacos.config.group} configuration, use DEFAULT_GROUP by default. To customize your own Group, perform the following configurations:

spring.cloud.nacos.config.group=YOUR_GROUP_NAME

NOTE:

This configuration must be placed in the bootstrap.properties file. And the value of the Group when add configuration must and spring.cloud.nacos.config.group The Group's configuration values.

Customize the Dataid configuration for the extension

Spring Cloud Alibaba Nacos Config since version 0.2.1, can support the configuration of custom Data Id. A detailed design of this section can be found here. A complete configuration example is as follows:

spring.application.name=opensource-service-provider
spring.cloud.nacos.config.server-addr=127.0.0.1:8848

# config external configuration

1. The Data Id is in the default group DEFAULT_GROUP, which does not support dynamic refresh of the configuration
spring.cloud.nacos.config.extension-configs[0].data-id=ext-config-common01.properties

# 2. Data Id is not in the default group and does not support dynamic refresh

spring.cloud.nacos.config.extension-configs[1].data-id=ext-config-common02.properties
spring.cloud.nacos.config.extension-configs[1].group=GLOBALE_GROUP

# 3. Data Id is not in the default group and supports dynamic refresh
spring.cloud.nacos.config.extension-configs[2].data-id=ext-config-common03.properties
spring.cloud.nacos.config.extension-configs[2].group=REFRESH_GROUP
spring.cloud.nacos.config.extension-configs[2].refresh=true

You can see:

  • through spring.cloud.nacos.config.extension-configs[n].data-id way to support multiple data id configuration.

  • through spring.cloud.nacos.config.extension-configs[n].group configuration way custom Data Id group, without explicitly configured, the default is DEFAULT_GROUP.

  • through spring.cloud.nacos.config.extension-configs[n].refresh configuration way to control the Data Id when configuration changes, whether to support applications dynamically refresh, to perceive the latest configuration values. The default is not supported.

Note:

Multiple Data Id configuration at the same time, his priority relation is spring.cloud.nacos.config.extension-configs[n].data-id where n value, the greater the higher priority.

spring.cloud.nacos.config.extension-configs[n].data-id must take file extensions, file extensions can support the properties, and can support yaml/yml. The spring.cloud.nacos.config.file-extension configuration of custom extensions configuration Data Id file extension.

By customizing extended Data ids, you can solve the configuration sharing problem among multiple applications and support multiple configuration files for one application.

To make it clearer how to configure shared Data ids across multiple applications, you can do so in the following ways:

Configure Data ids that support sharing
spring.cloud.nacos.config.shared-configs[0].data-id=common.yaml

The default group is DEFAULT_GROUP
spring.cloud.nacos.config.shared-configs[0].group=GROUP_APP1

Data Id Whether to refresh dynamically when the configuration changes. The default value is false
spring.cloud.nacos.config.shared-configs[0].refresh=true

You can see:

  • through spring.cloud.nacos.config.shared-configs[n].data-id to support multiple Shared data id configuration.

  • through spring.cloud.nacos.config.shared-configs[n].group to configure a custom Data Id group, without explicitly configured, the default is DEFAULT_GROUP.

  • through spring.cloud.nacos.config.shared-configs[n].refresh to control the Data Id when configuration changes, whether to support applications dynamically refresh, false by default.

The priority of the configuration

Nacos Config currently offers three configuration capabilities to pull relevant configurations from Nacos.

  • A: through spring.cloud.nacos.config.shared-dataids support multiple Shared Data Id configuration;

  • B: through spring.cloud.nacos.config.ext-config[n].data-id The data-id way to support multiple extended data id configuration;

  • C: Automatically generates related Data ids based on internal rules (application name, application name + Profile).

When the three methods are used together, one of their priority relationships is: A < B < C

Configuration items

More configuration items for Nacos Config Starter are as follows:

Configuration itemkeyDefault valueDescription
Server addressspring.cloud.nacos.config.server-addrip address and port number of the server
DataId prefixspring.cloud.nacos.config.prefix${spring.application.name}The prefix of the DataId. The default value is the application name
Groupspring.cloud.nacos.config.groupDEFAULT_GROUP
DataId suffix and content file formatspring.cloud.nacos.config.file-extensionpropertiesThe DataId suffix, which is also the configuration content file format, currently supports only properties
Configure the encoding mode of the contentspring.cloud.nacos.config.encodeUTF-8Configured coding
Gets the configured timeout periodspring.cloud.nacos.config.timeout3000Unit: ms
The configured namespacespring.cloud.nacos.config.namespaceOne common scenario is the separation and isolation of different environments, such as resource isolation between the development and test environments and production environments.
AccessKeyspring.cloud.nacos.config.access-key
SecretKeyspring.cloud.nacos.config.secret-key
Relative pathspring.cloud.nacos.config.context-pathThe relative path of the server API
Access pointspring.cloud.nacos.config.endpointDomain name of a service in a region. Through this domain name, the server address can be dynamically obtained
Whether to enable listening and automatic refreshspring.cloud.nacos.config.refresh-enabledtrue
Cluster service namespring.cloud.nacos.config.cluster-name

Endpoint information

Request http://127.0.0.1:18084/actuator/nacosconfig address, you can see related EndPoint node information:

$ curl http://127.0.0.1:18084/actuator/nacosconfig

Response:

{
"NacosConfigProperties": {
"serverAddr": "127.0.0.1:8848",
"username": "",
"password": "",
"encode": null,
"group": "DEFAULT_GROUP",
"prefix": "PREFIX",
"fileExtension": "properties",
"timeout": 3000,
"maxRetry": null,
"configLongPollTimeout": null,
"configRetryTime": null,
"enableRemoteSyncConfig": false,
"endpoint": null,
"namespace": "NAMESPACE",
"accessKey": null,
"secretKey": null,
"ramRoleName": null,
"contextPath": null,
"clusterName": null,
"name": null,
"sharedConfigs": null,
"extensionConfigs": null,
"refreshEnabled": true,
"configServiceProperties": {
"encode": "",
"secretKey": "",
"serveraddr": "127.0.0.1:8848",
"prefix": "PREFIX",
"configLongPollTimeout": "",
"maxRetry": "",
"password": "",
"configRetryTime": "",
"endpoint": "",
"serverAddr": "127.0.0.1:8848",
"accessKey": "",
"enableRemoteSyncConfig": "false",
"clusterName": "",
"namespace": "NAMESPACE",
"ramRoleName": "",
"username": "",
"group": "DEFAULT_GROUP"
},
"refreshableDataids": null,
"extConfig": null,
"sharedDataids": null
},
"RefreshHistory": [],
"Sources": [
{
"lastSynced": "2023-05-10 09:35:50",
"dataId": "nacos-config-example.properties"
}
]
}

Nacos Service Registration and Discovery Advanced Guide

Principle

Spring Cloud Nacos Discovery complies with Spring Cloud Common standards and implements three interfaces: AutoServiceRegistration, ServiceRegistry and Registration.

In Spring Cloud application startup phase, monitor the WebServerInitializedEvent event, when the Web container initialization complete, namely receive WebServerInitializedEvent incident, will trigger action, register the service with Nacos Server by calling the register method of ServiceRegistry.

IPv4 to IPv6 address migration scheme

Dual registration of IPv4 and IPv6 addresses

After Spring Cloud Loadbalancer is configured as a load balancing policy, IPv4 and IPv6 addresses of micro-services are registered with the registry by default after the application starts. IPv4 addresses are stored under the IP field in the Nacos service list. IPv6 address In the metadata field of Nacos, the corresponding Key is IPv6. When a service consumer invokes a service provider, it selects the appropriate IP address type to initiate the service invocation based on its own IP address stack support.

Specific rules:

  1. If the service consumer supports dual IPv4 and IPv6 address stacks or only supports IPv6 address stacks, the service consumer will use the IPv6 address provided by the service to initiate service invocation. If the IPv6 address invocation fails, the service consumer cannot switch to IPv4 address stacks and initiate retry invocation.
  2. If the service consumer supports only IPv4 single-address stack, the service consumer invokes the service using the IPv4 address provided by the service.

Only IPv4 is registered

If you only want to register using IPv4 addresses, you can use the following configuration in application.properties:

spring.cloud.nacos.discovery.ip-type=IPv4

Only IPv6 is registered

If you only want to use IPv6 addresses, you can use the following configuration in application.properties:

spring.cloud.nacos.discovery.ip-type=IPv6

Configuration items

For more information about the starter configuration items of spring-cloud-starter-alibaba-nacos-discovery, see the following:

Configuration itemkeyDefault valueDescription
Server addressspring.cloud.nacos.discovery.server-addr
Service namespring.cloud.nacos.discovery.service${spring.application.name}The name of the service registered with Nacos, which defaults to the application name
Weightspring.cloud.nacos.discovery.weight1The value ranges from 1 to 100. A larger value indicates a larger weight
Nic namespring.cloud.nacos.discovery.network-interfaceIf no IP address is configured, the registered IP address is the IP address of the NIC. If this parameter is not configured, the IP address of the first NIC is used by default
Registered IP addressspring.cloud.nacos.discovery.ipHighest priority
Type of the registered IP addressspring.cloud.nacos.discovery.ip-typeDouble-stack addressYou can configure the IPv4 and IPv6 two types, if the network card IP address multiple same type, hope to develop a specific network segment address, can use spring. Cloud. Inetutils. Preferred - networks address configuration screen
Registered portspring.cloud.nacos.discovery.port-1By default, you do not need to configure this parameter
namespacespring.cloud.nacos.discovery.namespaceOne of the most common scenarios is the separation and isolation of the registration of different environments, such as the isolation of resources (such as configurations and services) between the development test environment and the production environment.
AccessKeyspring.cloud.nacos.discovery.access-key
SecretKeyspring.cloud.nacos.discovery.secret-key
Metadataspring.cloud.nacos.discovery.metadataThe configuration is in Map format
Log file namespring.cloud.nacos.discovery.log-name
clusterspring.cloud.nacos.discovery.cluster-nameDEFAULTNacos Cluster name
Access pointspring.cloud.nacos.discovery.endpointDomain name of a service in a region. Through this domain name, the server address can be dynamically obtained
Whether to integrate LoadBalancerspring.cloud.loadbalancer.nacos.enabledfalse
Whether to enable Nacos Watchspring.cloud.nacos.discovery.watch.enabledfalseYou can set it to true to enable watch
Whether to enable Nacosspring.cloud.nacos.discovery.enabledtrueStart by default. If set to false, automatic registration with Nacos is disabled

Endpoint Information

Request http://127.0.0.1:18083/actuator/nacosdiscovery Address,You can view information about the EndPoint node

$ curl http://127.0.0.1:18083/actuator/nacosdiscovery

Response:

{
"subscribe": [],
"NacosDiscoveryProperties": {
"serverAddr": "127.0.0.1:8848",
"username": "nacos",
"password": "nacos",
"endpoint": "",
"namespace": "",
"watchDelay": 30000,
"logName": "",
"service": "service-consumer",
"weight": 1,
"clusterName": "DEFAULT",
"group": "DEFAULT_GROUP",
"namingLoadCacheAtStart": "false",
"metadata": {
"IPv6": null,
"preserved.register.source": "SPRING_CLOUD"
},
"registerEnabled": true,
"ip": "192.168.3.19",
"networkInterface": "",
"ipType": null,
"port": 18083,
"secure": false,
"accessKey": "",
"secretKey": "",
"heartBeatInterval": null,
"heartBeatTimeout": null,
"ipDeleteTimeout": null,
"instanceEnabled": true,
"ephemeral": true,
"failureToleranceEnabled": false,
"failFast": true,
"nacosProperties": {
"password": "nacos",
"endpoint": "",
"secretKey": "",
"serverAddr": "127.0.0.1:8848",
"accessKey": "",
"clusterName": "DEFAULT",
"namespace": "",
"com.alibaba.nacos.naming.log.filename": "",
"namingLoadCacheAtStart": "false",
"failFast": "true",
"username": "nacos"
}
}
}