Table of contents
1. The key features of Nacos include:
2. Introduction to logical architecture and its components
3. Download the source code or installation package
4. How to introduce Nacos Discovery Starter
5. Start a Provider application
1 pom.xml configuration. A complete pom.xml configuration looks like this:
2 application.properties configuration.
3 Start the Provider example. As follows:
5 Start a Consumer application
6. More configuration item information about Nacos Starter
1. The key features of Nacos include:
-
Service discovery and service health monitoring
Nacos supports DNS-based and RPC-based service discovery. The service provider usesnative SDK, OpenAPI, or a >Independent Agent TODOAfter registering the Service, the service consumer can use DNS TODO or < /span>Lookup and discovery services. HTTP&API
Nacos provides real-time health checks on services and prevents requests from unhealthy hosts or service instances. Nacos supports health checks at the transport layer (PING or TCP) and application layer (such as HTTP, MySQL, user-defined). For health check of services in complex cloud environments and network topology environments (such as VPC, edge networks, etc.), Nacos provides two health check modes: agent reporting mode and server-side active detection. Nacos also provides a unified health check dashboard to help you manage service availability and traffic based on health status.
-
Dynamic configuration service
Dynamic configuration service allows you to manage application configuration and service configuration of all environments in a centralized, external and dynamic manner.
Dynamic configuration eliminates the need to redeploy applications and services when configuration changes, making configuration management more efficient and agile.
Centralized management of configuration makes it easier to implement stateless services and elastically expand services on demand.
Nacos provides a simple and easy-to-use UI (Console Sample Demo) to help you manage the configuration of all services and applications. Nacos also provides a series of out-of-the-box configuration management features including configuration version tracking, canary release, one-click rollback of configuration, and client configuration update status tracking to help you manage configurations in a production environment more securely. Change and reduce the risk associated with configuration changes.
-
Dynamic DNS service
The dynamic DNS service supports weighted routing, making it easier for you to implement middle-tier load balancing, more flexible routing policies, traffic control, and simple DNS resolution services for the data center intranet. Dynamic DNS services also make it easier to implement service discovery based on the DNS protocol, helping you eliminate the risk of coupling to vendor-proprietary service discovery APIs.
Nacos provides some simpleDNS APIs TODO to help you manage the associated domain names and available IP:PORT lists of services.
-
Services and their metadata management
Nacos allows you to manage all services and metadata in the data center from the perspective of microservice platform construction, including management service descriptions, life cycles, static dependency analysis of services, service health status, service traffic management, routing and security policies , service SLA and the most important metrics statistics.
2. Introduction to logical architecture and its components
-
Service management: implement service CRUD, domain name CRUD, service health status check, service weight management and other functions
-
Configuration management: realize configuration management CRUD, version management, grayscale management, monitoring management, push track, aggregate data and other functions
-
Metadata management: Provides metadata CURD and marking capabilities
-
Plug-in mechanism: realize the ability of three modules to be separated and combined, and realize the extension point SPI mechanism
-
Event mechanism: implement asynchronous event notification, SDK data change asynchronous notification and other logic
-
Log module: manage log classification, log level, log portability (especially to avoid conflicts), log format, exception code + help documentation
-
Callback mechanism: SDK notifies data and calls back to user processing through a unified mode. Interfaces and data structures need to be extensible
-
Addressing mode: Solve multiple addressing modes such as IP, domain name, nameserver, broadcast, etc., need to be scalable
-
Push channel: Solve push performance problems between server and storage, between servers, and between server and SDK
-
Capacity management: Manage the capacity of each tenant and group to prevent storage from being overwritten and affecting service availability.
-
Traffic management: Control request frequency, number of long links, packet size, and request flow control according to multiple dimensions such as tenants and groups.
-
Caching mechanism: disaster recovery directory, local cache, server cache mechanism. Tools are required to use the disaster recovery directory
-
Startup mode: Start different programs + UI according to stand-alone mode, configuration mode, service mode, dns mode, or all mode
-
Consistency protocol: solves different data, different consistency requirements, and different consistency mechanisms
-
Storage module: solve data persistence, non-persistent storage, and solve data fragmentation problems
-
Nameserver: Solve the routing problem from namespace to clusterid, and solve the mapping problem between user environment and nacos physical environment
-
CMDB: Solve the problem of metadata storage, docking with third-party cmdb system, and solve the relationship between applications, people and resources.
-
Metrics: Expose standard metrics data to facilitate connection with third-party monitoring systems
-
Trace: Exposes standard trace to facilitate connection with SLA system, log whitening, push trace and other capabilities, and can be connected with metering and billing system
-
Access management: equivalent to the process of activating Alibaba Cloud services and assigning identities, capacities, and permissions
-
User management: Solve user management, login, sso and other issues
-
Permission management: Solve issues such as identity recognition, access control, role management, etc.
-
Audit system: Extended interface to facilitate connection with audit systems of different companies
-
Notification system: Core data changes or operations can be easily communicated through the SMS system to notify the corresponding person of data changes.
-
OpenAPI: Exposes standard Rest style HTTP interface, simple and easy to use, convenient for multi-language integration
-
Console: Easy-to-use console for service management, configuration management and other operations
-
SDK: multi-language sdk
-
Agent: dns-f similar mode, or integrated with mesh and other solutions
-
CLI: The command line performs lightweight management of products, as easy to use as git
3. Nacos installation
Service discovery is one of the most critical components in the microservice architecture system. It is very difficult to manually configure the service list of all service providers for each client, and it is not conducive to the dynamic expansion and contraction of services. Nacos Discovery Starter can help you automatically register services to the Nacos server and can dynamically sense and refresh the service list of a service instance. In addition, Nacos Discovery Starter also registers some metadata information of the service instance itself - such as host, port, health check URL, home page, etc. - to Nacos.
1. Version selection
It is recommended that you use version 2.X. The currently recommended stable version is 2.1.1.
2. Prepare the environment
Nacos relies on Java environment to run. If you build and run Nacos from code, you also need to configure the Maven environment for this. Please make sure you install and use it in the following version environment:Maven a>
- 64 bit OS, supports Linux/Unix/Mac/Windows, Linux/Unix/Mac is recommended.
- 64 bit JDK 1.8+;下载 & Placement.
- Maven 3.2.x+;Download & Placement .
3. Download the source code or installation package
You can obtain Nacos through source code and distribution package.
Download source code from Github
git clone https://github.com/alibaba/nacos.git
cd nacos/
mvn -Prelease-nacos -Dmaven.test.skip=true clean install -U
ls -al distribution/target/
// change the $version to your actual path
cd distribution/target/nacos-server-$version/nacos/bin
Download the compiled compressed package method
unzip nacos-server-$version.zip 或者 tar -xvf nacos-server-$version.tar.gz
cd nacos/bin
4. Start the server
- Note: Nacos needs to be run with a machine configuration of at least 2C4g60g*3.
Linux/Unix/Mac
Startup command (standalone represents stand-alone mode operation, not cluster mode):
sh startup.sh -m standalone
If you are using an ubuntu system, or if you run the script and get an error message [[ symbol cannot be found, you can try running as follows:
bash startup.sh -m standalone
Windows
Startup command (standalone represents stand-alone mode operation, not cluster mode):
startup.cmd -m standalone
5. Shut down the server
Linux/Unix/Mac
sh shutdown.sh
Windows
shutdown.cmd
4. How to introduce Nacos Discovery Starter
If you want to use Nacos for service discovery in your project, use the starter with the group ID com.alibaba.cloud and the artifact ID spring-cloud-starter-alibaba-nacos-discovery.
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
5. Start a Provider application
The following steps show you how to register a service with Nacos.
1 pom.xml configuration. A complete pom.xml configuration looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>open.source.test</groupId>
<artifactId>nacos-discovery-test</artifactId>
<version>1.0-SNAPSHOT</version>
<name>nacos-discovery-test</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>${spring.boot.version}</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring.cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring.cloud.alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2 application.properties configuration.
Some basic configurations about Nacos must also be configured in application.properties (or application.yaml), as shown below: application.properties
server.port=8081
spring.application.name=nacos-producer
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
management.endpoints.web.exposure.include=*
If you don't want to use Nacos for your service registration and discovery, you can set spring.cloud.nacos.discovery.enabled to false.
3 Start the Provider example. As follows:
@SpringBootApplication
@EnableDiscoveryClient
public class NacosProviderDemoApplication {
public static void main(String[] args) {
SpringApplication.run(NacosProducerDemoApplication.class, args);
}
@RestController
public class EchoController {
@GetMapping(value = "/echo/{string}")
public String echo(@PathVariable String string) {
return "Hello Nacos Discovery " + string;
}
}
}
At this time, you can see the registered service information on the Nacos console.
Please start the Nacos service before starting the Provider application. For specific startup methods, please refer to Nacos official website .
4 EndPoint of the service
spring-cloud-starter-alibaba-nacos-discovery provides an EndPoint during implementation. The access address of EndPoint is http://ip:port/actuator/nacos-discovery. EndPoint information mainly provides two categories:
1. subscribe: shows which service subscribers are currently available
2. NacosDiscoveryProperties: Displays the basic configuration of Nacos for the current service instance
The information for a service instance to access EndPoint is as follows:
{
"subscribe": [
{
"jsonFromServer": "",
"name": "nacos-provider",
"clusters": "",
"cacheMillis": 10000,
"hosts": [
{
"instanceId": "30.5.124.156#8081#DEFAULT#nacos-provider",
"ip": "30.5.124.156",
"port": 8081,
"weight": 1.0,
"healthy": true,
"enabled": true,
"cluster": {
"serviceName": null,
"name": null,
"healthChecker": {
"type": "TCP"
},
"defaultPort": 80,
"defaultCheckPort": 80,
"useIPPort4Check": true,
"metadata": {
}
},
"service": null,
"metadata": {
}
}
],
"lastRefTime": 1541755293119,
"checksum": "e5a699c9201f5328241c178e804657e11541755293119",
"allIPs": false,
"key": "nacos-producer",
"valid": true
}
],
"NacosDiscoveryProperties": {
"serverAddr": "127.0.0.1:8848",
"endpoint": "",
"namespace": "",
"logName": "",
"service": "nacos-provider",
"weight": 1.0,
"clusterName": "DEFAULT",
"metadata": {
},
"registerEnabled": true,
"ip": "30.5.124.201",
"networkInterface": "",
"port": 8082,
"secure": false,
"accessKey": "",
"secretKey": ""
}
}
5 Start a Consumer application
A Consumer application may not be as simple as starting a Provider application. Because the Consumer side needs to call the REST service provided by the Provider side. In the example, we use the most primitive method, which is to explicitly use LoadBalanceClient and RestTemolate to access it. For the configuration of pom.xml and application.properties, please refer to 1.2 Summary. The sample code to start a Consumer application is as follows:
@SpringBootApplication
@EnableDiscoveryClient
public class NacosConsumerApp {
@RestController
public class NacosController{
@Autowired
private LoadBalancerClient loadBalancerClient;
@Autowired
private RestTemplate restTemplate;
@Value("${spring.application.name}")
private String appName;
@GetMapping("/echo/app-name")
public String echoAppName(){
//使用 LoadBalanceClient 和 RestTemolate 结合的方式来访问
ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-provider");
String url = String.format("http://%s:%s/echo/%s",serviceInstance.getHost(),serviceInstance.getPort(),appName);
System.out.println("request url:"+url);
return restTemplate.getForObject(url,String.class);
}
}
//实例化 RestTemplate 实例
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(NacosConsumerApp.class,args);
}
}
In this example, we inject an instance of LoadBalancerClient, manually instantiate a RestTemplate, and inject the configuration value of spring.application.name into the application. The purpose is that when calling the service provided by the Provider, we hope that the currently configured application The name is displayed.
Please start the Nacos service before starting the Consumer application. For specific startup methods, please refer to Nacos official website .
After startup, access the http://ip:port/echo/app-name interface provided by Consumer. The port I started testing here is 8082. The access results are as follows:
Access address: http://127.0.0.1:8082/echo/app-name
Access results: Hello Nacos Discovery nacos-consumer
6. More configuration item information about Nacos Starter
More starter configuration items about spring-cloud-starter-alibaba-nacos-discovery are as follows:
Configuration items |
Key |
default value |
illustrate |
Server address |
spring.cloud.nacos.discovery.server-addr |
none |
Nacos Server starts listening ip address and port |
Service Name |
spring.cloud.nacos.discovery.service |
${spring.application.name} |
Name the current service |
Service grouping |
spring.cloud.nacos.discovery.group |
DEFAULT_GROUP |
Set the group in which the service is located |
Weights |
spring.cloud.nacos.discovery.weight |
1 |
The value range is 1 to 100. The larger the value, the greater the weight. |
Network card name |
spring.cloud.nacos.discovery.network-interface |
none |
When the IP is not configured, the registered IP is the IP address corresponding to the network card. If this item is not configured, the address of the first network card is taken by default. |
Registered IP address |
spring.cloud.nacos.discovery.ip |
none |
highest priority |
Registered port |
spring.cloud.nacos.discovery.port |
-1 |
By default, no configuration is required and it will be detected automatically. |
Namespaces |
spring.cloud.nacos.discovery.namespace |
none |
One of the common scenarios is the differentiation and isolation of registrations in different environments, such as the isolation of resources (such as configurations and services) between development and testing environments and production environments. |
AccessKey |
spring.cloud.nacos.discovery.access-key |
none |
When going to Alibaba Cloud, a cloud account name on Alibaba Cloud |
SecretKey |
spring.cloud.nacos.discovery.secret-key |
none |
When going to Alibaba Cloud, a cloud account password on Alibaba Cloud |
Metadata |
spring.cloud.nacos.discovery.metadata |
none |
Using Map format configuration, users can customize some service-related metadata information according to their own needs. |
Log file name |
spring.cloud.nacos.discovery.log-name |
none |
|
cluster |
spring.cloud.nacos.discovery.cluster-name |
DEFAULT |
Configure it as Nacos cluster name |
Access Point |
spring.cloud.nacos.discovery.enpoint |
UTF-8 |
The entrance domain name of a certain service in the region. The server address can be obtained dynamically through this domain name. |
Whether to integrate Ribbon |
ribbon.nacos.enabled |
true |
Generally, it can be set to true |
Whether to turn on Nacos Watch |
spring.cloud.nacos.discovery.watch.enabled |
true |
Can be set to false to turn off watch |
Registered IP address type |
spring.cloud.nacos.discovery.ip-type |
IPv4 |
Both IPv4 and IPv6 types can be configured |
Results:Nacos discovery · alibaba/spring-cloud-alibaba Wiki · GitHub