[Spring Cloud] In-depth understanding of Nacos' unified configuration management, configuration hot update, multi-environment configuration sharing, and cluster construction


Preface: Why unified configuration management is needed

In microservice architecture, configuration management is a crucial issue. As the size of the system increases, the management and updating of configurations become more cumbersome. As a comprehensive service discovery and configuration management platform, Nacos provides comprehensive support to solve this problem. In this article, we will have an in-depth understanding of Nacos configuration management, including unified management of configurations, hot updates, multi-environment configuration sharing, and the construction of Nacos clusters.

1. Nacos configuration management

1.1 Add configuration file in Nacos

Nacos provides an intuitive Web interface that allows us to easily add and manage configuration files. Through the Web interface, we can add corresponding configuration information for different microservices, including database connections, port numbers, etc.

The following will demonstrate how to add a new configuration file on the Nacos console:

  1. First, click Configuration Management in the Nacos console, and then select the plus sign on the right to add a new configuration:

  2. Then set the following configuration information, and finally click Publish:

In this configuration information, the Data ID is specified userservice-dev.yml, and a date format is set in the configuration content.

Instructions on the Data ID naming format:

  1. First, ensure the uniqueness of the Data ID. Use a specific service name to ensure uniqueness;
  2. Adopt Servicename-profilethe format of , where profilerepresents the running environment of the current service, such as dev.
  3. Configuration files can be of various types, such as yml, propertiesetc. According to the configuration of different formats, the suffix name of the Data ID will be different. For example, using userservice-dev.ymlas Data ID indicates that the configuration file is in YAML format.

Instructions on configuration content:

Configuration content usually includes application parameters, settings, and other information related to the operation of the application. This configuration information may include but is not limited to:

  1. Database connection information: including database URL, user name, password, etc.

  2. Service port number: The port on which the application runs and is used to handle external requests.

  3. Addresses and keys for third-party services: Information required when interacting with other services.

  4. Log level and format: Control the verbosity and format of application log output.

  5. Cache strategy: Configure cache size, expiration time and other related parameters.

  6. Security configuration: includes configuration information related to authentication and authorization.

  7. Task scheduling configuration: Configure the execution strategy and parameters of scheduled tasks.

  8. Other runtime parameters: such as thread pool size, connection timeout, etc.

The characteristic of configuration contents is that they often need to change, and the configurations in different environments may also be different. Therefore, properly managing and updating configuration information is crucial to the flexibility and maintainability of applications. By using configuration centers such as Nacos, configuration information can be centrally managed and dynamically updated to better adapt to changing applications.

1.2 Microservice obtains configuration

In microservice applications, obtaining configuration information is a critical task. Configuration information includes database connections, service ports, addresses of third-party services, log settings, etc. This information is crucial for the correct operation of the application. The process of microservices obtaining configuration information is different when there is no Nacos configuration and when there is Nacos configuration.

1.2.1 Without Nacos configuration

In the absence of Nacos configuration center, the steps for microservices to obtain configuration information are as follows:

Without Nacos configuration

illustrate:

  1. When the project starts, the application reads local configuration files, which are usually stored in the classpath, such as application.propertiesor application.yml.
  2. Subsequently, the application will create a Spring container based on the content in the configuration file and load the relevant Bean objects.
  3. When the application needs to obtain configuration information, it will obtain it directly from the Spring container.

1.2.2 With Nacos configuration

In the case of Nacos configuration center, the steps for microservices to obtain configuration information are as follows:

With Nacos configuration

illustrate:

  1. In the case of Nacos configuration, you first need to know the address of the Nacos configuration center and the configuration file information. This information is typically stored in the application's bootstrap.ymlor bootstrap.properties.
  2. When the project is started, the application will first read bootstrap.ymlthe configuration and obtain the address of the Nacos configuration center and other necessary information.
  3. Subsequently, the application will connect to the Nacos configuration center to obtain configuration information. These configuration information include database connections, addresses of third-party services, log settings, etc.
  4. After obtaining the Nacos configuration information, the application will read the local configuration file again, such as application.propertiesor application.yml.
  5. Finally, the application will merge the Nacos configuration and the local configuration, create a Spring container, and load related Bean objects.

With the Nacos configuration center, Nacos acts as a centralized configuration management center, allowing microservices to dynamically obtain configuration information and achieve centralized management of configurations, thus improving flexibility and maintainability.

1.3 Modification of local configuration files

  1. Introduce Nacos configuration management client dependencies:
<!--nacos配置管理依赖-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
  1. Add a file in the directory . user-serviceThis file is a boot file and has a higher priority than :resourcebootstrap.ymlapplication.yml
spring:
  application:
    name: userservice # 服务名称
  profiles:
    active: dev #开发环境,这里是 dev
  cloud:
    nacos:
      server-addr: localhost:8848 # Nacos 地址
      config:
        file-extension: yaml  # 文件后缀名

After adding a new bootstrap.ymlconfiguration file, you can application.ymldelete duplicate configuration items.

1.4 Code to obtain configuration information

After all configurations have been modified, how to prove that the configuration was successful? At this point, you can use the code to read and see if you can read the configuration information added in Nacos. Reading configuration information can be done using @Valueannotations.

For example, modify UserControllerthe code in as follows:

@Value("${pattern.dateformat}")
private String dateformat;

@GetMapping("now")
public String now() {
    
    
    return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateformat));
}

Then restart the server and use a browser to access nowthis interface:

The time is successfully output, indicating that the new configuration in Nacos has also taken effect successfully.

2. Hot update of configuration files

2.1 Modify configuration file

At this time, if we want to modify the configuration content in Nacos, for example, the format of the modification date is as follows:

After the modification is completed, access it through the browser again and find that it does not take effect:

If you restart user-servicethe service and access it through the browser again, it will take effect:

But if you want to modify the configuration file, it will take effect immediately, and in the actual production environment, it will also take effect. You can't just restart the server just because you modified a little configuration information, so what should you do at this time?

2.2 Set up configuration file hot update

To achieve this goal, you need to use hot update of the configuration file. That is, after the configuration file in Nacos is changed, the microservice can detect it without restarting. In the code, there are two ways to implement hot update of configuration files:

Method 1: @ValueAdd an annotation to the class where the injected variable is located. @RefreshScopeAnnotation

After adding the annotation, restart the microservice. The current access output time format is as follows:


Then, modify the time format in the Nacos configuration file again:

At this time, the microservice is not restarted and is accessed directly through the browser. The output time format is as follows. If it matches the format just modified, it means that the hot update configuration is successful:

And at this time, user-servicethe console will also output information related to the relevant configuration files:

Method 2: Use @ConfigurationPropertiesannotations

When using @ConfigurationPropertiesannotations, the content read from the configuration file will be encapsulated into an object, so you first need to create a class:

@Component
@Data
@ConfigurationProperties(prefix = "pattern")
public class PatternProperties {
    
    
    private String dateformat;
}

Then modify UserControllerthe code in and comment out the relevant code in method 1:

@Autowired
private PatternProperties properties;

@GetMapping("now")
public String now() {
    
    
    return LocalDateTime.now().format(DateTimeFormatter.ofPattern(properties.getDateformat()));
}

Restart the microservice. At this time, the time format output by the access browser is as follows:

Then modify the date format in the Nacos configuration file again:

At this time, the microservice is not restarted and is accessed directly through the browser. The output time format is as follows. If it matches the format just modified, it means that the hot update configuration is successful:

3. Multi-environment configuration sharing

In microservice applications, it is usually necessary to use different configuration information in different environments (development, testing, production, etc.). However, if the configuration content in multiple environments is the same, in order to avoid repeated configurations, multi-environment configuration files can be shared. Nacos provides a simple and effective way to achieve this goal.

3.1 Shared configuration file naming

3.1 Shared configuration file naming

When the microservice starts, when reading multiple configuration files from Nacos, the following naming convention is used:

  • [spring.application.name]-[spring.profiles.active].yaml,For example:userservice-dev.yaml
  • [spring.application.name].yaml,For example:userservice.yaml

Regardless spring.profiles.activeof the changes, [spring.application.name].yamlthis file will be loaded. Therefore, configurations shared by multiple environments can be written to this file.

Example:

Assuming spring.application.name, userservicethe corresponding configuration file is named as follows:

  • userservice.yaml: Shared configuration file, containing configurations common to all environments.
server:
  port: 8080
database:
  url: jdbc:mysql://localhost:3306/userservice
  username: admin
  password: admin123
  • userservice-dev.yaml: Development environment configuration file, covering configuration items that need to be changed.
spring:
  profiles:
    active: dev
database:
  url: jdbc:mysql://localhost:3306/userservice_dev
  • userservice-test.yaml: Test environment configuration file, which also covers configuration items that need to be changed.
spring:
  profiles:
    active: test
database:
  url: jdbc:mysql://testdb:3306/userservice_test

Such a naming convention makes maintaining configurations in different environments clearer and more convenient, while ensuring that the same configuration information can be shared in multiple environments.

3.2 Set up multi-environment configuration file sharing

Add a new configuration file to the Nacos environment list userservice.yaml:


After adding the shared configuration file, modify PatternPropertiesthe class again UserControllerto read the shared configuration information:

PatternPropertiesClass :

@Component
@Data
@ConfigurationProperties(prefix = "pattern")
public class PatternProperties {
    
    
    private String dateformat;
    private String envSharedValue;
}

UserControllerkind:

@GetMapping("prop")
public PatternProperties properties(){
    
    
    return properties;
}

Then restart the user-serviceservice. Note that the current environment of this service is devthe environment, and the corresponding port number is 8081.

In addition, open another user-serviceservice with the port number 8082 so that it is in testthe environment, but there is no need to create a configuration file. You can set it directly through IDEA:


Since no testenvironment configuration file has been created, it can be inferred that all other fields of the service corresponding to the 8082 port except shared environment variables should be null.

Access propthe interfaces of these two services respectively, and the results are as follows:


At this point, the configuration file sharing has been successfully implemented.

3.3 Priority of configuration files

If different configuration files have different attributes, what is the priority of the configuration files? In fact, the answer to this question can be easily found. That is to set the same properties in different configuration files, and see which one the final result is based on to determine the priority relationship.

  1. application.ymlFirst, add the following content to the local configuration file :

    and modify PatternPropertiesthe code:
@Component
@Data
@ConfigurationProperties(prefix = "pattern")
public class PatternProperties {
    
    
    private String dateformat;
    private String envSharedValue;
    private String name; 
}

There is no doubt that what is read at this time is the local configuration, because this attribute is not configured in Nacos.

  1. userservice.yamlThen set this property in the Nacos configuration file

Refresh the browser and find that the shared configuration file prevails, so we conclude that Nacos's shared configuration file has a higher priority than the local configuration file.

  1. Then userservice-dev.yamlalso set this attribute in


Refresh the browser and find that the development configuration file of Nacos prevails. Therefore, it is concluded that the priority of the Nacos development environment configuration file is greater than the shared configuration file.

To sum up, the priority relationship of different configuration files is as follows:

  • Service name-profile.yaml > Service name.yaml > Local configuration

In more detail, in Nacos configuration management, configuration files from different sources have different priorities. The priority order from high to low is as follows:

  1. Environment configuration (Profile): Environment configuration has the highest priority. When using configuration files named in [spring.application.name]-[spring.profiles.active].yamlthe format of Nacos, where spring.profiles.activewill specify the current environment, the highest priority.

  2. Service name.yaml: A configuration file named in [spring.application.name].yamlthe format, where is spring.application.namethe service name. This is a common configuration at the service level and has higher priority.

  3. extension-config: Configuration obtained through the configuration item Data IDin the Nacos configuration center. extension-configThis configuration item is usually used for extended configuration, such as customized business configuration.

  4. extension-configs: Configuration obtained through the configuration item Data IDin the Nacos configuration center. extension-configsThis configuration item is also used for extended configuration, but has extension-configa lower priority than a separate one.

  5. shared-configs: Configuration obtained through the configuration item Data IDin the Nacos configuration center. shared-configsThis configuration item is usually used for shared configuration, such as common configuration agreed within the team.

  6. Local configuration: Local configuration is a configuration item specified directly in the application and has the lowest priority. This includes configuration items defined in the application's configuration files (such as application.ymlor ).application.properties

Priority example:

Suppose there is a microservice named userserviceand the current environment is dev, then the priority order is:

  • userservice-dev.yaml(Environment configuration) > userservice.yaml(service name.yaml) > extension-config> extension-configs> shared-configs> Local configuration

This priority rule ensures that configuration items can be flexibly managed and overridden in configurations at different levels and sources, thereby achieving more granular configuration control.

4. Nacos cluster construction

Building a Nacos cluster is a key step to ensure system availability and fault tolerance. Through cluster deployment, you can share the load, improve the system's concurrent processing capabilities, and maintain the normal operation of the system when a node fails.

The following are the basic steps to build a Nacos cluster:

  • Build the database and initialize the database table structure
  • Download nacos installation package
  • Configure nacos
  • Start nacos cluster
  • nginx reverse proxy

The following is a detailed explanation of the construction process.

4.1 Cluster structure diagram

Official Nacos cluster diagram:

It contains 3 nacos nodes, and then a load balancer proxy 3 Nacos. This load balancer can use nginx.

Planned cluster structure:

The addresses of the three nacos nodes:

node IP PORT
nacos1 192.168.150.1 8845
nacos2 192.168.150.1 8846
nacos3 192.168.150.1 8847

4.2 Initialize database

Nacos default data is stored in the embedded database Derby, which is not a production-available database.

The officially recommended best practice is to use a high-availability database cluster with master-slave, but here we take a single-point database as an example.

First create a new database, name it nacos, and then import the following SQL:

CREATE TABLE `config_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(255) DEFAULT NULL,
  `content` longtext NOT NULL COMMENT 'content',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  `app_name` varchar(128) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  `c_desc` varchar(256) DEFAULT NULL,
  `c_use` varchar(64) DEFAULT NULL,
  `effect` varchar(64) DEFAULT NULL,
  `type` varchar(64) DEFAULT NULL,
  `c_schema` text,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfo_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info_aggr   */
/******************************************/
CREATE TABLE `config_info_aggr` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(255) NOT NULL COMMENT 'group_id',
  `datum_id` varchar(255) NOT NULL COMMENT 'datum_id',
  `content` longtext NOT NULL COMMENT '内容',
  `gmt_modified` datetime NOT NULL COMMENT '修改时间',
  `app_name` varchar(128) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfoaggr_datagrouptenantdatum` (`data_id`,`group_id`,`tenant_id`,`datum_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='增加租户字段';


/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info_beta   */
/******************************************/
CREATE TABLE `config_info_beta` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL COMMENT 'content',
  `beta_ips` varchar(1024) DEFAULT NULL COMMENT 'betaIps',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfobeta_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_beta';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info_tag   */
/******************************************/
CREATE TABLE `config_info_tag` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `tenant_id` varchar(128) DEFAULT '' COMMENT 'tenant_id',
  `tag_id` varchar(128) NOT NULL COMMENT 'tag_id',
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL COMMENT 'content',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfotag_datagrouptenanttag` (`data_id`,`group_id`,`tenant_id`,`tag_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_tag';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_tags_relation   */
/******************************************/
CREATE TABLE `config_tags_relation` (
  `id` bigint(20) NOT NULL COMMENT 'id',
  `tag_name` varchar(128) NOT NULL COMMENT 'tag_name',
  `tag_type` varchar(64) DEFAULT NULL COMMENT 'tag_type',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `tenant_id` varchar(128) DEFAULT '' COMMENT 'tenant_id',
  `nid` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`nid`),
  UNIQUE KEY `uk_configtagrelation_configidtag` (`id`,`tag_name`,`tag_type`),
  KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_tag_relation';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = group_capacity   */
/******************************************/
CREATE TABLE `group_capacity` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `group_id` varchar(128) NOT NULL DEFAULT '' COMMENT 'Group ID,空字符表示整个集群',
  `quota` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值',
  `usage` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '使用量',
  `max_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
  `max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数,,0表示使用默认值',
  `max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
  `max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最大变更历史数量',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_group_id` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='集群、各Group容量信息表';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = his_config_info   */
/******************************************/
CREATE TABLE `his_config_info` (
  `id` bigint(64) unsigned NOT NULL,
  `nid` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `data_id` varchar(255) NOT NULL,
  `group_id` varchar(128) NOT NULL,
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL,
  `md5` varchar(32) DEFAULT NULL,
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `src_user` text,
  `src_ip` varchar(50) DEFAULT NULL,
  `op_type` char(10) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`nid`),
  KEY `idx_gmt_create` (`gmt_create`),
  KEY `idx_gmt_modified` (`gmt_modified`),
  KEY `idx_did` (`data_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='多租户改造';


/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = tenant_capacity   */
/******************************************/
CREATE TABLE `tenant_capacity` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `tenant_id` varchar(128) NOT NULL DEFAULT '' COMMENT 'Tenant ID',
  `quota` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值',
  `usage` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '使用量',
  `max_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
  `max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数',
  `max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
  `max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最大变更历史数量',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='租户容量信息表';


CREATE TABLE `tenant_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `kp` varchar(128) NOT NULL COMMENT 'kp',
  `tenant_id` varchar(128) default '' COMMENT 'tenant_id',
  `tenant_name` varchar(128) default '' COMMENT 'tenant_name',
  `tenant_desc` varchar(256) DEFAULT NULL COMMENT 'tenant_desc',
  `create_source` varchar(32) DEFAULT NULL COMMENT 'create_source',
  `gmt_create` bigint(20) NOT NULL COMMENT '创建时间',
  `gmt_modified` bigint(20) NOT NULL COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_tenant_info_kptenantid` (`kp`,`tenant_id`),
  KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='tenant_info';

CREATE TABLE `users` (
	`username` varchar(50) NOT NULL PRIMARY KEY,
	`password` varchar(500) NOT NULL,
	`enabled` boolean NOT NULL
);

CREATE TABLE `roles` (
	`username` varchar(50) NOT NULL,
	`role` varchar(50) NOT NULL,
	UNIQUE INDEX `idx_user_role` (`username` ASC, `role` ASC) USING BTREE
);

CREATE TABLE `permissions` (
    `role` varchar(50) NOT NULL,
    `resource` varchar(255) NOT NULL,
    `action` varchar(8) NOT NULL,
    UNIQUE INDEX `uk_role_permission` (`role`,`resource`,`action`) USING BTREE
);

INSERT INTO users (username, password, enabled) VALUES ('nacos', '$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu', TRUE);

INSERT INTO roles (username, role) VALUES ('nacos', 'ROLE_ADMIN');

4.3 Configure Nacos

Enter the conf directory of nacos, modify the configuration file cluster.conf.example, and rename it to cluster.conf:

Then add the address:

127.0.0.1:8845
127.0.0.1.8846
127.0.0.1.8847

Then modify the application.properties file and add database configuration

spring.datasource.platform=mysql

db.num=1

db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user.0=root
db.password.0=123

4.4.Startup

Copy the nacos folder into three copies and name them respectively: nacos1, nacos2, nacos3

Then modify the application.properties in the three folders respectively,

nacos1:

server.port=8845

nacos2:

server.port=8846

nacos3:

server.port=8847

Then start three nacos nodes respectively:

startup.cmd

4.5.nginx reverse proxy

Install nginx to a non-Chinese directory:

Modify conf/nginx.confthe file and configure it as follows:

upstream nacos-cluster {
    server 127.0.0.1:8845;
	server 127.0.0.1:8846;
	server 127.0.0.1:8847;
}

server {
    listen       80;
    server_name  localhost;

    location /nacos {
        proxy_pass http://nacos-cluster;
    }
}

Then visit: in the browser http://localhost/nacos.

The file configuration in the code application.ymlis as follows:

spring:
  cloud:
    nacos:
      server-addr: localhost:80 # Nacos地址

4.6.Optimization

  • During actual deployment, you need to set a domain name for the nginx server that is used as a reverse proxy, so that if there is a server that migrates the nacos client later, there is no need to change the configuration.

  • Each node of Nacos should be deployed to multiple different servers to ensure disaster recovery and isolation.

Guess you like

Origin blog.csdn.net/qq_61635026/article/details/133431996