Spring Cloud Alibaba (2) Nacos unified configuration management

Table of contents

1. Why do we need a configuration center

2. Commonly used configuration centers

Several concepts of Nacos

3. Use of Nacos Configuration Center

(1) properties format

1. Import dependencies

2. Create a new configuration in the configuration center

3. Modify the configuration file name to bootstrap.yml

4. Add the configuration of the nacos config service address in the microservice

5. Test to obtain the configuration of the registration center

(2) yaml format

(3) profiles.active—granularity configuration

Frequently appearing error messages:

common error


insert image description here

1. Why do we need a configuration center

Before there was no configuration center, traditional application configuration had the following pain points:

(1) Using local static configuration, real-time performance cannot be guaranteed: configuration modification is inflexible and requires a long test and release cycle, and the client cannot be notified as soon as possible. Some configurations have high requirements for real-time performance, such as active-standby switching configuration Or you need to modify the configuration when you encounter a failure. At this time, if you configure it through traditional static configuration or republishing, the response speed is very slow and the business risk is very high.

(2) It is easy to cause production accidents: for example, when releasing, it is easy to bring the configuration of the test environment to production, causing production accidents.

(3) The configuration is scattered and the format is not standard: some use the properties format, some use the xml format, and some save it in DB. The team tends to make its own wheels, with various methods.

(4) The configuration lacks security audit, version control, and configuration authority control functions: who? what time? What configuration has been modified? There is no way to trace back, and it is impossible to roll back to the previous version in time if something goes wrong; it is impossible to authenticate and authorize the release of configuration changes, and everyone can modify and publish the configuration.

    而配置中心区别于传统的配置信息分散到系统各个角落的方式,对系统中的配置文件进行集中统一管理,而不需要逐一对单个的服务器进行管理。那这样做有什么好处呢?
After using the configuration center

(1) By unifying the format of the configuration center, the configuration can be standardized,

(2) When the configuration information changes, the modification takes effect in real time, and the corresponding changes can be automatically sensed without restarting the server, and the new changes are uniformly sent to the corresponding programs to quickly respond to changes. For example, a certain function is only for users in a certain area, and a certain function is only available during the big promotion period. After using the configuration center, only relevant personnel need to dynamically adjust the parameters in the configuration center, and it can be basically real-time or quasi-real-time. Adjust the corresponding business.

(3) Problems can also be traced through the audit function

2. Commonly used configuration centers

There are three mainstream solutions for the configuration center in microservices: Nacos, Apollo, Config+Bus, but here we mainly introduce the usage of Nacos as the configuration center.

insert image description here

Several concepts of Nacos

Namespace (Namespace)
Namespace can be used to isolate the configuration of different environments. Generally, an environment is divided into a namespace
configuration group (Group)
Configuration group is used to classify different services into the same group. Generally, the configuration of a project is divided into a set of
configuration sets (Data ID)
In ​​the system, a configuration file is usually a configuration set. The configuration of a general microservice is a configuration set
insert image description here

3. Use of Nacos Configuration Center

Using nacos as the configuration center is actually treating nacos as a server and each microservice as a client. We store the configuration files of each microservice on nacos, and then each microservice pulls the configuration from nacos. Can.

It is equivalent to the service module requesting nacos, and nacos responds to the service module with some data

(1) properties format

1. Import dependencies

Which service module needs to obtain the data of nacos configuration management, add dependencies on that module

<!--nacos的config配置中心依赖-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!--把application.yml配置文件名称改为bootstrap.xml-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>

2. Create a new configuration in the configuration center

 

3. Modify the configuration file name to bootstrap.yml

4. Add the configuration of the nacos config service address in the microservice

spring:
  application:
    name: user-server #注册服务的名称
  # 配置数据源
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/nacos?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: 123456
  #clout配置nacos服务注册中心
  cloud:
    nacos:
      discovery: #配置客户端
        server-addr: 192.168.100.129:8848 #虚拟机ip地址和端口号
        username: nacos #nacos网址的账号密码
        password: nacos
      #配置nacos网站的config配置中心
      config:
        server-addr: 192.168.100.129:8848 #虚拟机ip地址和端口号
        file-extension: properties #配置内容的类型格式
        username: nacos #nacos网站的账号密码
        password: nacos

5. Test to obtain the configuration of the registration center

@RestController
@RequestMapping("/user")
public class UserController {

    @Value("${username}")//通过配置中心的配置内容的键获取value
    public String username;

    @Value("${age}")//通过配置中心的配置内容的键获取value
    public String age;

    @GetMapping("/test2")
    public void test2(){
        System.out.println(username); //控制台打印张三
        System.out.println(age);//99
    }

}

6. You can move the configuration of the database in the yml configuration file to the configuration center, and modify the configuration of the data source in the project

Obtain the configuration content data source configuration of the configuration center in the user service module, so that the database can be configured successfully, and the data source configuration in the yml configuration file can be deleted

@Configuration
public class DataSourceConfig {
    @Value("${spring.datasource.druid.username}")
    private String username;
    @Value("${spring.datasource.druid.password}")
    private String password;
    @Value("${spring.datasource.druid.url}")
    private String url;
    @Value("${spring.datasource.druid.driver-class-name}")
    private String driverClassName;
    @Bean
    public DataSource dataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        druidDataSource.setDriverClassName(driverClassName);
        return druidDataSource;
    }
}

(2) yaml format

1. Create a new configuration in the configuration center

insert image description here

2. Modify the project configuration file name to bootstrap.yml and modify the configuration file configuration

insert image description here

(3) profiles.active—granularity configuration

1. Create a configuration in the configuration center

data id: service name-namespace name.suffix name (order-server-dev.yaml)

insert image description here

2. Engineering module configuration

insert image description here

Frequently appearing error messages:

org.springframework.beans.factory.BeanCreationException: @Value did not inject successfully, check it carefully

common error

1. If it fails to start and reports an error, the possible problem is: the firewall is not closed, and then open the Nacos service after closing the firewall

View fire status

systemctl status firewalld

img

systemctl stop firewalld

Then go to start the Nacos service

2. If the startup is successful, it is found that there is no data and registration information on the nacos service registration center website, it may be that the network of the machine has changed

Because the IP address in the conf/application.properties file is the IPv4 address of the current network attribute, if the network is changed, the IP address needs to be modified

# 启用standalone模式
nacos.standalone=true
# 修改端口号
server.port=8848
# 修改数据存储位置
spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://192.168.216.176:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=root
db.password=123456

注意要修改以下参数: 

server.port: Change to the port number to be used db.url.0: Change to the connection address of the MySQL database. The IP address is the IPv4 address of the current network attribute. If you change the network, it will change. Remember to modify it

db.user, db.password: and set the correct database user name and password

Guess you like

Origin blog.csdn.net/m0_65992672/article/details/130734777