What is Nacos?
It’s official 🔈
- Nacos is a dynamic service discovery, configuration management, and service management platform that makes it easier to build cloud-native applications.
- Service is a first-class citizen of the Nacos world.
Liverpoolfc.tv: nacos. IO/useful – cn /
How to understand these two sentences? That is, Nacos provides not only service registration and discovery, but also configuration management, as well as a visual management platform. Nacos, in turn, revolves around services.
If you look at the source code, you will find that the core API of Nacos defines two interfaces, NamingService and ConfigService. Service registration and discovery revolves around NamingService, and configuration management revolves around ConfigService.
-
Summary: Nacos is a combination of registry + configuration center
-
Equivalent: Nacos = Eureka+Config+Bus
The four core features of Nacos 👇
Service discovery and service health monitoring
- Nacos makes it easier to register services and discover other services through DNS or HTTP interfaces, and it also provides real-time health checks of services to prevent requests from being sent to unhealthy hosts or service instances.
Dynamically configured service
- Dynamically configuring services allows you to manage the configuration of all services in a centralized and dynamic manner in all environments. Nacos eliminates the need to redeploy the application when the configuration is updated, making configuration changes more efficient and flexible.
Dynamic DNS Service
- Nacos provides service discovery capability based on DNS protocol, aiming to support service discovery of heterogeneous languages, and support to expose endpoints of services registered in Nacos in the way of domain name, so that third-party applications can easily search and discover.
Service and metadata management
- Nacos enables you to manage all services and metadata in your data center from a microservices platform construction perspective, including managing service descriptions, life cycles, static dependency analysis of services, health of services, traffic management of services, routing, and security policies.
What are the advantages of nacos config over springcloud config? 👇
-
Most springCloud Config scenarios are used in conjunction with Git, and dynamic changes also rely on the Spring Cloud Bus message Bus for all client changes.
-
Springcloud Config does not provide a visual interface.
-
Nacos Config uses a long connection to update the configuration, and notifies the Provider of any changes to the configuration very quickly, killing SpringCloud’s original config by several blocks in speed.
Why use Nacos when you have Eureka in your registry? 👇
-
Eureka 2.0 is closed.
-
According to the official website, the number of registered instances of NACOS is larger than that of Eureka.
-
Because of the RAFT protocol used by NACOS, the consistency of nacOS clusters is much greater than that of Eureka clusters.
Raft agreement
Raft, a distributed consistency protocol, has been popular in the technical field since the paper was published in 2013. Compared with other distributed consistency algorithms, Raft is relatively simple and easy to implement, which is also the main factor that Raft can rise to prominence.
Raft protocol relies heavily on the Leader node to ensure cluster data consistency. That is, all the data sent by the client reaches the Leader node first. After receiving the data, the Leader marks the data as uncommitted. Then the Leader copies the data to all followers and waits for the response. After receiving a response indicating that the data has been received by more than N/2 followers in the cluster, the Leader marks the committed status of the data and sends a message to the client indicating that the data has been received. Sending notifications to all the Follower nodes indicates that the data is in committed state.
Download and install Nacos
- Make sure your local Java8+Maven environment is ok before downloading
Download: github.com/alibaba/nac…
Decompress the installation package and run startup. CMD in the bin directory
After the success of the operation directly to http://localhost:8848/nacos
- The default account and password are both
nacos
If you want to use Docker to download, install Nacos and complete persistent configuration, click the link at the back to jump to 👉 Docker download, install Nacos and complete persistent configuration
Nacos domain model
Due to the complexity of the project application environment and considering the effective storage and management of all kinds of data, different model structures are provided for data classification and storage in Nacos.
- Namespace: Isolates different environments, such as development, test, and production environments.
- Group: Grouping several services or configuration sets into a Group, usually one system into a Group. Recommended naming format:
Product name + group name
- Service: a Service, such as membership micro services.
In hierarchical storage model of the image below you can see, in the level of service, save the health check switch, metadata, the routing mechanism, and protection of the threshold Settings, save the health examination and cluster model, metadata, data synchronization mechanism, instance holds the IP, port, the weight of the instance, state of health examination, offline, metadata, the response time.
- Cluster: Cluster is a logical concept that distinguishes the network environment where different service nodes reside.
- Instance: Stores specific micro-service registration data. Each service node corresponds to one Instance data.
- DataId (configuration DataId) : user-defined configuration data set recommended naming format:
Package name. Class name (lowercase)
You can see the corresponding interface on the NACOS console
If that doesn’t make sense, we can look directly at how namespaces, groups, and Services are stored at the code level.
/** * Map(namespace, Map(group::serviceName, Service)). */
private final Map<String, Map<String, Service>> serviceMap = new ConcurrentHashMap<>();
Copy the code
The Nacos service registry is structured as Map. The namespace-based design of Nacos is designed to isolate multi-environment and multi-tenant data (configuration and service). If you have multiple environments (such as development, test, and production environments), you can create three different namespaces.
In this case, we ignore the one-to-many case. If there is only one Namespace, its entire hierarchy includes Namespace containing multiple groups, Group containing multiple services, Service containing multiple clusters, and Cluster containing Instance sets.
// ServiceManager class, Map(namespace, Map(group::serviceName, Service))
private final Map<String, Map<String, Service>> serviceMap = new ConcurrentHashMap<>();
// Service class Map(cluster, cluster)
private Map<String, Cluster> clusterMap = new HashMap<>();
/ / Cluster classes
private Set<Instance> persistentInstances = new HashSet<>();
private Set<Instance> ephemeralInstances = new HashSet<>();
/ / Instance class
private String instanceId;
private String ip;
private int port;
private double weight = 1.0 D;
Copy the code
Instances are divided into temporary instances and persistent instances. The key difference is the way the health check is done. Temporary instances use client-side reporting mode, while persistent instances use server-side reverse probing mode.
Temporary instances need to be able to automatically remove unhealthy instances without persisting the instance. Persistent instances use server-side health checks because clients do not report heartbeats and cannot automatically remove offline instances.
Nacos as the registry
A registry is the address book of the microservices architecture. It records the mapping between services and service addresses. In a distributed architecture, services are registered here, and when a service needs to call another service, it finds the address of the service and makes the call.
The registry mainly consists of three parts: service registry, service provider and service consumer
Nacos registry instance culling policy
The policy of service registration is to send a heartbeat to the NacOS server every 5 seconds, with the service name, service IP, service port and other information. In addition, the NACOS Server initiates a health check to the client and supports TCP/HTTP checks. If no heartbeat is detected within 15 seconds and the health check fails, the instance is considered unhealthy. If the health check fails within 30 seconds, the instance is deleted.
Nacos Server and Client
Nacos registry is divided into Server and Client. Nacos provides SDK and openApi. If there is no SDK, the openApi can also be used to manually write service registration, discovery and configuration of pull logic.
The Server is written in Java and based on the Spring Boot framework, providing registration and discovery services and configuration services for the Client. Client support includes currently known Nacos multilingual clients and related clients of the Spring ecosystem. Clients and microservices are nested together.
The DNS implementation of Nacos relies on CoreDNS and its project is nacOS-CoreDNS-Plugin. The plug-in provides a DNS-F client based on CoreDNS, developed in go.
Registry usage
Nacos version demonstrated in this paper is 1.1.3, SpringCloud version is 2.1.0.release, SpringCloud-Alibaba version is Greenwich.SR3, springboot version is 2.1.8.RELEASE.
1. Add dependencies
Maven dependency for NacOS
<! -- NacOS service registration/discovery -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-nacos-discovery</artifactId>
</dependency>
Copy the code
In order to introduce overhead dependency, first of all, it is necessary to confirm that this project is a boot project, and also to introduce springcloud-Alibaba dependency. If you really cannot modify it, please refer to the poM file below.
<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>
<! Fill in your gVA coordinates below -->
<groupId>com.xxx</groupId>
<artifactId>xxx-xxx</artifactId>
<version>1.0 the SNAPSHOT</version>
<! -- Version Control -->
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR3</spring-cloud.version>
</properties>
<dependencies>
<! -- NacOS service registration/discovery -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.0. RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
Copy the code
2. Write a configuration file
Declare the address of the registry to be registered with, the name of the service, etc
spring:
cloud:
nacos:
discovery:
server-addr: xx.xxx.xxx.xx:8848 Registry address
application:
name: lgmall-coupon # service name
server:
port: 8010 # port
Copy the code
3. Write startup classes
Use the @enableDiscoveryClient annotation to enable service registration and discovery on our startup class
@EnableDiscoveryClient
Copy the code
4. Test
After successful startup, we open the registry console and can view the successfully registered microservices.
Nacos serves as the configuration center
In a microservice architecture, when the system is split from a single application into service nodes on a distributed system, the configuration files must be migrated (split) as well, so that the configuration is dispersed. Moreover, the decentralization involves redundancy, as shown in the figure below
To solve this situation, configuration centers were born. The configuration center separates configurations from applications and manages configurations in a unified manner. The application itself does not need to manage the configuration itself.
Nacos configures the central architecture
The configuration hub itself is not complicated, if you leave the CAP trade-offs aside. The basic function of the configuration center is to store a key-value pair. Users publish a configKey and the client obtains the configValue. The advanced feature is that when a configuration item changes, the change tells the client to refresh the old value.
The architecture diagram below briefly describes the rough architecture of a configuration center. Users can publish configurations through the management platform, register configurations with the server through HTTP calls, and the server stores them in persistent storage engines such as MySQL. The user accesses the configuration of the server through the CLIENT SDK and establishes HTTP long polling to listen for configuration item changes. In addition, to reduce the pressure on the server and ensure the DISASTER recovery feature, after the configuration item is pulled from the client, a snapshot is saved in a local file. The SDK takes precedence over the contents in the file.
Configure the usage of the center
The configuration center is consistent with all versions of the registry.
1. Add dependencies
Introduce the Nacos Config Starter dependency.
<! -- NacOS Configuration Center -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
Copy the code
2. Modify the configuration file
Create the bootstrap.properties configuration file and configure the nacOS Config metadata
- Bootstrap. properties takes precedence over yML files
spring.application.name=lgmall-coupon
spring.cloud.nacos.config.server-addr=xx.xxx.xxx.xx:xxxx
Copy the code
3. Add configuration rules on the console
Add a config center called Data Id lgmall-batch.properties.
- The default rules
Application of the properties
4. Write Java code
Remote configuration is read via @Value, and the @refreshScope annotation is added to ensure dynamic configuration RefreshScope
@RefreshScope
@RestController
@RequestMapping("coupon/coupon")
public class CouponController {
@Autowired
private CouponService couponService;
@Value("${user.ponName}")
private String name;
@GetMapping("/test")
public R test(a){
return R.ok().put("name",name); }}Copy the code
5. Test
After a successful startup, we call the interface to see the final result and find that we have successfully read the value of the configuration center
How to use Nacos configuration center in real life
- Create a namespace. Create a different namespace for each environment in the microservice project, using groups to distinguish between different microservices
- To create a configuration set, take the following project as an example. We need to group the five microservices except common and create their configuration files. Here we take the Test test environment as an example
After creation, the overall effect is as follows
- Read multiple configuration sets and refresh dynamicallyMicroservices Any configuration information can be placed in the configuration center
bootstrop.properties
Before SpringBoot any method of getting a value from a configuration file (e.g.@Value
@ConfigurationProerties
) can be used, configuration center has priority to read configuration center.
# bootstrap.properites takes precedence over YML files
spring.application.name=lgmall-coupon
spring.cloud.nacos.config.server-addr=xx.xxx.xxx.xx:8848
Use the configuration under which namespace to write to. Note that the unique ID of the namespace to write to cannot write to the name
spring.cloud.nacos.config.namespace=ef375233-21be-646b-b955-6f3e0d855951
Configure data sources
spring.cloud.nacos.config.ext-config[0].data-id=datasource.yaml
spring.cloud.nacos.config.ext-config[0].group=coupon
spring.cloud.nacos.config.ext-config[0].refresh=true
#mybatis
spring.cloud.nacos.config.ext-config[1].data-id=mybatis.yaml
spring.cloud.nacos.config.ext-config[1].group=coupon
spring.cloud.nacos.config.ext-config[1].refresh=true
# nacOS-related configuration
spring.cloud.nacos.config.ext-config[2].data-id=nacos.yaml
spring.cloud.nacos.config.ext-config[2].group=coupon
spring.cloud.nacos.config.ext-config[2].refresh=true
# Other configuration
spring.cloud.nacos.config.ext-config[3].data-id=other.yaml
spring.cloud.nacos.config.ext-config[3].group=coupon
spring.cloud.nacos.config.ext-config[3].refresh=true
Copy the code
Data-id indicates the specific configuration, group indicates the read group, and refresh=true indicates the dynamic refresh. You can see the following figure
- Start and test
Yaml, other.yaml, nacos.yaml. mybatis.yaml
Located property source: CompositePropertySource {name='NACOS', propertySources=[NacosPropertySource {name='lgmall-coupon.properties'}, NacosPropertySource {name='other.yaml'}, NacosPropertySource {name='nacos.yaml'}, NacosPropertySource {name='mybatis.yaml'}, NacosPropertySource {name='datasource.yaml'}}]Copy the code
We accessed the database and found the request successful!