Introduction to Nacos
Nacos is an easy-to-use dynamic service discovery, configuration and service management platform for building cloud-native applications
Key features of Nacos include the following:
- Service discovery and service health monitoring: After the service provider registers the service using native SDK, OpenAPI, etc., the service consumer can use HTTP&API to find and discover the service. Nacos provides real-time health checks on services and prevents requests from unhealthy hosts or service instances.
- 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.
- Dynamic DNS service: 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 data center intranets
- Service and metadata management: Nacos manages all services and metadata in the data center from the perspective of microservice platform construction, including management service description, life cycle, static dependency analysis of services, service health status, service traffic management, Routing and security policies, service SLAs, and primary metrics statistics
Nacos quick start
1. Nacos Server stand-alone mode
Before using Nacos, you need to download Nacos and start Nacos Server. Nacos Server has two operating modes: standalone (single machine) and cluster (cluster). Here we take 2.2.3.release, windows environment as an example
前往 Github 下载 Nacos Server:GitHub - alibaba/nacos: an easy-to-use dynamic service discovery, configuration and service management platform for building cloud native applications.
Unzip the compressed package and execute the command in the bin directory.\startup.cmd -m standalone
Visit: http://localhost:8848/nacos in the browser, enter the user name and password Nacos/Nacos to enter the Nacos homepage
To shut down Nacos, execute the command in the bin directory.\shutdown.cmd
Nacos before version 0.7 used an inline database to store data in stand-alone mode, which was inconvenient to observe the basic situation of data storage. After version 0.7, it supports MySQL data source capabilities. The specific operation steps are as follows:
-
Install MySQL database (version 5.6.5+ required)
-
Create the database nacos_config, find the mysql-schema.sql initialization file in the conf directory and initialize it
-
Modify the conf/applicationproperties file and add MySQL data source configuration
### Count of DB: db.num=1 ### Connect URL of DB: db.url.0=jdbc:mysql://127.0.0.1:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC db.user.0=root db.password.0=123
-
Afterwards, all data in Nacos will be saved to MySQL
2. Nacos Server cluster mode
Nacos stand-alone mode is only suitable for testing and stand-alone use. Most production environments use cluster mode to ensure high availability.
Next, we will explain how to build a Nacso cluster environment. The specific steps are as follows:
-
Copy the downloaded Nacos installation package into two copies and name them Nacos-01, Nacos-02, and Nacos-03 respectively. Note that the cluster mode must use a configuration database (such as MySQL)
-
Modify the configuration files conf/applicationproperties of Nacos-02 and Nacos-03, and change the service startup ports to 8850 and 8852 respectively.
#*************** Config Module Related Configurations ***************# ### If use MySQL as datasource: ### Deprecated configuration property, it is recommended to use `spring.sql.init.platform` replaced. spring.datasource.platform=mysql spring.sql.init.platform=mysql #*************** Spring Boot Related Configurations ***************# ### Default web context path: server.servlet.contextPath=/nacos ### Include message field server.error.include-message=ALWAYS ### Default web server port: server.port=8850
Note: After version 2.0, nacos also occupies three other ports in addition to the external port:
- raft port: ${server.port} - 1000
- grpc port: ${server.port} + 1000
- grpc port for server: ${server.port} + 1001
Assume that the external port is 8848, that is, a total of 4 ports will be occupied, namely 7848, 8848, 9848, and 9849. Therefore, when starting multiple nacos nodes on the same machine, be careful to avoid all occupied ports.
-
Add cluster.conf cluster configuration file in the conf directory of Nacos-01, Nacos-02, and Nacos-03
### 这里简单将3个nacos实例部署在同一个机器下 # 127.0.0.1:8848 127.0.0.1:8850 127.0.0.1:8852
-
Enter the bin directory of Nacos-01, Nacos-02, and Nacos-03 to execute the command
.\startup.cmd
. If there are no parameters, the default is cluster mode.
3. Nacos+Nginx cluster mode
Add the following configuration to the Nginx core configuration file nginx.conf
server {
listen 8847;
server_name localhost;
location /nacos {
proxy pass http://nacos-server/nacos;
}
upstream nacos-server {
server 127.0.0.1:8848;
server 127.0.0.1:8850;
server 127.0.0.1:8852;
}
}
Start Nginx and visit: http://localhost:8847/nacos. At this point we have completed the construction of Nacos+Nginx.
SpringBoot registered to Nacos
1. Nacos configuration management
Taking SpringBoot 2.3.12.RELEASE as an example, add the following dependencies to the project's pom.xml file:
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>0.2.12</version>
</dependency>
Configure the address of Nacos Server in application.properties
# 如果搭建了集群只需要填其中一个节点的ip:port即可
nacos.config.server-addr=127.0.0.1:8848
# 如果配置了Nginx,则输入配置的地址,如上面我配置的
# nacos.config.server-addr=127.0.0.1:8847/nacos
Use in the startup class to @NacosPropertySource
load dataId as the configuration source of springboot-nacos-config and enable automatic updates.
@SpringBootApplication
@NacosPropertySource(dataId = "springboot-nacos-config", autoRefreshed = true)
public class SpringbootNacosApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootNacosApplication.class, args);
}
}
Data-Id: springboot-nacos-config
Of course, we need to add the configuration file to the Nacos configuration list
test.name=hahaha
@NacosValue
Set property values through Nacos annotations
@RestController("config")
public class ConfigCon {
@NacosValue(value = "${test.name}", autoRefreshed = true)
private String name;
@GetMapping("get")
public String get() {
return name;
}
}
2. Nacos service registration
Add the following dependencies to the project's pom.xml file:
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>
<version>0.2.12</version>
</dependency>
Configure the address of Nacos Server in application.properties
spring.application.name=springboot-nacos
server.port=8080
server.address=127.0.0.1
# 如果搭建了集群只需要填其中一个节点的ip:port即可
nacos.discovery.server-addr=127.0.0.1:8848
# 如果配置了Nginx,则输入配置的地址,如上面我配置的
nacos.discovery.server-addr=127.0.0.1:8847/nacos
Modify the startup class and run it
@SpringBootApplication
@NacosPropertySource(dataId = "springboot-nacos-config", autoRefreshed = true)
public class SpringbootNacosApplication implements CommandLineRunner {
// 使用@NacosInjected注入Nacos的NamingService实例
// NamingService是Nacos对外提供给使用者的接口
@NacosInjected
private NamingService namingService;
@Value("${spring.application.name}")
private String applicationName;
@Value("${server.port}")
private Integer serverPort;
@Value("${server.address}")
private String serverAddress;
public static void main(String[] args) {
SpringApplication.run(SpringbootNacosApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
//应用启动时,将服务注册到Nacos
namingService.registerInstance(applicationName, serverAddress, serverPort);
}
}
Nacos SpringCloud
This section mainly explains how SpringCloud implements configuration management and service discovery through Nacos, taking SpringBoot 2.3.12.RELEASE as an example.
1. Nacos configuration management
Add the following dependencies to the project's pom.xml file:
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.10-RC1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Configure the address of Nacos Server in application.properties
server.port=8080
spring.application.name=springcloud-nacos
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
# spring.cloud.nacos.config.server-addr=127.0.0.1:8847/nacos
spring.application.name
It will then form part of the Nacos configuration management datald field. In Nacos Spring Cloud, the complete format of datald is as follows:${prefix}-${spring.profile.active}.${file-extension}
${prefix}
: Defaults tospring.application.name
the value of , which can alsospring.cloud.Nacos.config.prefix
be configured through the configuration item${spring.profile.active}
: Profile corresponding to the current environment. Whenspring.profile.active
is empty, the corresponding connector-
will not exist, and the splicing format of datald becomes${prefix}.${file-extension}
${file-extension}
: The data format of the configuration content, you can configure the properties or yaml type through `spring.cloud.Nacos.config.file-extension·
Create the springcloud-nacos.properties configuration file in the Nacos configuration list
test.name=hahah
Develop Controller to obtain configuration
@RefreshScope
@RestController("config")
public class ConfigCon {
@Value("${test.name}")
private String name;
@GetMapping("get")
public String get() {
return name;
}
}
2. Nacos service registration
Add the following dependencies to the project's pom.xml file:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.10-RC1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Configure the address of Nacos Server in application.properties
server.port=8080
spring.application.name=springcloud-nacos
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8847/nacos
Add annotations to the startup class to @EnableDiscoveryClient
enable the service registration discovery function
@EnableDiscoveryClient
@SpringBootApplication
public class SpringcloudNacosApplication {
public static void main(String[] args) {
SpringApplication.run(SpringcloudNacosApplication.class, args);
}
}
Check the service list on the Nacos management page and find that the service has been registered to Nacos. Both the service provider and the consumer are registered in this way. After that, the consumer can directly call the provider's interface directly through the service name.
Namespaces & Groups
In addition to DataId, Nacos also provides namespace (Namespace) and configuration group (Group) for organizational configuration. The same Group or DataId configuration can exist in different Namespaces. In the same way, the same DataId can exist in different Groups
In general, it is best to use Namespace to distinguish environments (dev, sit, uat, prod), and Group to distinguish microservices or projects. Nacos' permission management can control namespaces, but not groups. Different accounts correspond to different environments and can isolate each environment.
In the Namespace named dev in the Nacos console, create a group named springcloud-project and a configuration file named service-01.yml under it.
Create bootstrap.yml configuration file under the project
server:
port: 8000
spring:
application:
name: service-01
cloud:
nacos:
config:
server-addr: 127.0.0.1:8847/nacos
namespace: 0178e474-2cfb-47c3-bded-da7cfa260f99 # 命名空间id
group: springcloud-project # 分组名
file-extension: yml # 指定格式
discovery:
server-addr: 127.0.0.1:8847/nacos
namespace: 0178e474-2cfb-47c3-bded-da7cfa260f99 # 命名空间id
group: springcloud-project # 分组名
Create a TestCon class and obtain configuration values
@Slf4j
@RestController
public class TestCon {
@Value("${test.value}")
private String testValue;
@GetMapping("/test/getConfig")
public void getConfig() {
log.info("testValue: {}", testValue);
}
}