Microservice study notes--(Nacos configuration management)

Nacos configuration management

  • Unified configuration management
  • Configure Hot Update
  • configuration sharing
  • Build a Nacos cluster

Nacos configuration management - Nacos implements configuration management

Unified configuration management

Configuration change hot update

Add configuration information in Nacos: configuration management-configuration list-+

Fill in the configuration information in the pop-up form:

Data ID:配置文件的id:[服务名称]-[profile].[后缀名]   # eg:orderservice-dev.yaml
Group: DEFAULT_GROUP #分组,默认即可
配置格式: 格式,目前支持yaml和properties
配置内容:# eg:
pattern:
  dataformat: yyyy-MM-dd HH:mm:ss

Nacos configuration management - microservice configuration pull

Unified configuration management

The steps to obtain the configuration are as follows:

Project start –> nacos address, bootstrap.yml –> read nacos configuration file –> read local configuration file application.yml –> create spring container –> load bean


1. Introduce Nacos configuration management client dependencies:

<!--nacos配置管理依赖-->
<dependency>
	<groupId>com.alibaba.cloud</groupId>
	<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

2. Add a bootstrap.yml file to the resource directory in userservice . This file is a bootstrap file with a higher priority than applicatin.yml

spring:
  application:
    name: userservice # 服务名称
  profiles:
    active: dev # 开发环境,这里是dev
  cloud:
    nacos:
      server-addr: localhost:8848 # Nacos地址
      config: 
        file-extension: yaml # 文件后缀名

Inject the pattern.dateformat attribute into UserController in user-service for testing:

@RestController
@RequestMapping("/user")
public class UserController {
    
    
	
	// 注入nacos中的配置属性
	@Value("${pattern.dateformat}")}
	private String dateformat;
	
	// 编写controller,通过日期格式化器来格式化现在时间并返回
	public String now() {
    
    
		return LocalDate.now().format(DateTimeFormatter.ofPattern(dataformat, Locale.CHINA));
	}
	...
}

summary:

Steps to hand over the configuration to Nacos management

  • Add configuration files in Nacos
  • Introduce nacos config dependencies in microservices
  • Add bootstrap.yml to the microservice, and configure the nacos address, current environment, service name, and file extension. These determine which file to read from nacos when the program starts

Nacos configuration management - configuration hot update

Configure automatic refresh

After the configuration file in Nacos is changed, the microservice can perceive it without restarting. However, you need to implement the following two configurations:

Method 1: Add annotation @RefreshScope on the class where the variable injected by @Value is located

@Slf4j
@RestController
@RequestMapping("/user")
@RefreshScope
public class UserController {
    
    
	
	@Value("${pattern.dateformat}")
	private String dateformat;
}

Method 2: Use @ConfigurationProperties annotation

@Component
@Data
@COnfigurationProperties(prefix = "pattern")
public class PatternProperties {
    
    
	private String dateformat;
}
@slf4j
@RestController
@RequestMapping("/user")
@RefreshScope
public class UserController {
    
    
	
	@Autowired
	private PatternProperties properties;
	 
	@GetMapping("now")
	public String now() {
    
    
		return LocalDateTime.now().format(DateTimeFormatter.ofPattern(properties.getDateformat()))
	}
}

summary:

After the Nacos configuration is changed, microservices can be hot updated in the following ways:

  • Injected through @Value annotation, combined with @RefreshScope to refresh
  • Injected through @ConfigurationProperties, automatically refreshed

Precautions:

  • Not all configurations are suitable to be placed in the configuration center, which is troublesome to maintain
  • It is recommended to put some key parameters and parameters that need to be adjusted at runtime into the nacos configuration center, which are generally custom configurations

Nacos configuration management - multi-environment configuration sharing

Multi-environment configuration sharing

When the microservice starts, it will read multiple configuration files from nacos:

  • [spring.application.name]-[spring.profiles.active].yaml,例如:userservice-dev.yaml

  • [spring.application.name].yaml,例如:userservice.yaml

No matter how the profile changes, the [spring.application.name].yaml file will be loaded, so multi-environment sharing configuration can be written to this file


Priority of various configurations:

service-name-profile.yaml > service-name.yaml > local-configuration

summary:

The configuration file that the microservice will read from nacos:

  • [service name]-[spring.profile.active].yaml, environment configuration
  • [service name].yaml, default configuration, multi-environment sharing

priority:

[service name]-[environment].yaml>[service name].yaml>local configuration


## Nacos configuration management-nacos cluster construction #### Nacos cluster construction

In the Nacos production environment, it must be deployed as a cluster state

1. Cluster structure diagram

The official Nacos cluster diagram:

DNS
SLB
Nacos Nacos Nacos

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

Addresses of three nacos nodes:

node ip port
nacos1 192.168.150.1 8845
nacos2 192.168.150.1 8846
nacos3 192.168.150.1 8847

2. Build a cluster diagram

The basic steps to build a cluster:

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

2.1. Initialize the 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 highly available database cluster with master-slave

Here is a single-point database as an example.

2.2. Download nacos

nacos has a download address on GitHub: https://github.com/alibaba/nacos/tags, you can choose any version to download.

2.3. Configure Nacos

Unzip the package to any non-Chinese directory, as shown in the figure:

  • bin
  • conf
  • target
  • LICENSE
  • NOTICE

Directory description:

  • bin: startup script
  • conf: configuration file

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

Then add content:

127.0.0.1:8845
127.0.0.1.8846
127.0.0.1.8847

Then modify the application.properties file and add the 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

2.4. Startup

Copy the nacos folder three times, namely: nacos1, nacos2, nacos3

Then modify the applicaiton.properties in the three folders respectively

nacos1:

server.port=8845

nacos2:

server.port=8846

nacos3:

server.port=8847

Then start three nacos nodes separately:
the default is cluster startup

startup.cmd

2.5.nginx reverse proxy

Unzip the nginx installation to any non-Chinese directory:

Modify the conf/nginx.conf file, the configuration is 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;
	}
}

In bootstrap.yml:

spring:
  application:
    name: userservice # 服务名称
  profiles:
    active: dev # 开发环境,这里是dev
  cloud:
    nacos:
      server-addr: localhost:80 # Nacos地址
      config: 
        file-extension: yaml # 文件后缀名

Browser access address:

http://localhost/nacos

summary:

Cluster construction steps

  • Build a MYSQL cluster and initialize the database table
  • Download and decompress nacos
  • Modify cluster configuration (node ​​information), database configuration
  • Start multiple nacos nodes separately
  • nginx reverse proxy

Guess you like

Origin blog.csdn.net/weixin_42594143/article/details/130573993
Recommended