SpringCloud microservice practice -- building an enterprise development framework: using Nacos distributed configuration center

Posted by mtimdog on Sun, 31 Oct 2021 02:56:28 +0100

With the development of business and the upgrading of micro service architecture, the number of services and the configuration of programs are increasing day by day (various micro services, various server addresses and various parameters). The traditional configuration file method and database method can not meet the requirements of developers for configuration management:

  • Security: the configuration follows the source code and is saved in the code base, which is easy to cause configuration leakage.
  • Timeliness: modifying the configuration requires restarting the service to take effect.
  • Limitations: dynamic adjustment cannot be supported, such as log switch and function switch.
    Therefore, the distributed configuration center came into being!
    Before using Nacos, first understand the loading sequence of the SpringBoot configuration file bootstrap and application:
  • bootstrap.yml (bootstrap.properties) is loaded first
  • Load after application.yml (application.properties)
  • bootstrap.yml is used for the boot phase of the application context
  • bootstrap.yml is loaded by the parent Spring ApplicationContext
    Nacos Config reads the bootstrap.yml configuration file by default. If the Nacos Config configuration is written to application.yml, errors will be reported all the time when the project is started.

1. The spring cloud starter Alibaba Nacos config dependency is introduced into gitegg platform cloud, a sub project of gitegg platform project, and the gitegg platform project is reinstalled. Then, the gitegg cloud project needs to execute Reload All Maven Projects in the IDEA again.

<!--?xml version="1.0" encoding="UTF-8"?-->
<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">
    <parent>
        <artifactid>GitEgg-Platform</artifactid>
        <groupid>com.gitegg.platform</groupid>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelversion>4.0.0</modelversion>

    <artifactid>gitegg-platform-cloud</artifactid>
    <name>${project.artifactId}</name>
    <version>${project.parent.version}</version>
    <packaging>jar</packaging>

    <dependencies>
        <!-- Nacos Service registration discovery-->
        <dependency>
            <groupid>com.alibaba.cloud</groupid>
            <artifactid>spring-cloud-starter-alibaba-nacos-discovery</artifactid>
        </dependency>
        <!-- Nacos Distributed configuration-->
        <dependency>
            <groupid>com.alibaba.cloud</groupid>
            <artifactid>spring-cloud-starter-alibaba-nacos-config</artifactid>
        </dependency>
    </dependencies>

</project>

2. Because the default reading service configuration of Nacos is written in bootstrap.yml, we create a bootstrap.yml file under gitegg service system project, and configure Nacos Config in bootstrap.yml

server:
  port: 8001
spring:
  application:
    name: gitegg-service-system
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
      config:
        server-addr: 127.0.0.1:8848
        file-extension: yml
        group: DEFAULT_GROUP
        enabled: true

3. Create a new gitegg-service-system.yaml configuration on the Nacos server, copy the configuration information in application.yml to the configuration information on the Nacos server, and then delete application.yml. In the Nacos Spring Cloud, the dataId   The complete format of the is as follows:

${prefix}-${spring.profiles.active}.${file-extension}
  • prefix   Default to   spring.application.name   The value of can also be configured through the configuration item   spring.cloud.nacos.config.prefix.
  • spring.profiles.active   This is the profile corresponding to the current environment. For details, please refer to   Spring Boot documentation .   Note: when   spring.profiles.active   When null, the corresponding connector  -  It will not exist, and the splicing format of dataId will become  $ {prefix}.${file-extension}
  • file-exetension   To configure the data format of the content, you can use the configuration item   spring.cloud.nacos.config.file-extension   To configure. Currently only supported   properties   and   yaml   Type.
    For detailed configuration information, please refer to   Spring Boot documentation
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://127.0.0.1/gitegg_cloud?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
    username: root
    password: root
    initialSize: 1
    minIdle: 3
    maxActive: 20
    # Configure the time to get the connection wait timeout
    maxWait: 60000
    # Configure how often to detect idle connections that need to be closed. The unit is milliseconds
    timeBetweenEvictionRunsMillis: 60000
    # Configure the minimum lifetime of a connection in the pool, in milliseconds
    minEvictableIdleTimeMillis: 30000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    # Open PSCache and specify the size of PSCache on each connection
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    # Configure the filters for monitoring statistics interception. After removal, the sql in the monitoring interface cannot be counted, 'wall' is used for firewall
    filters: config,stat,slf4j
    # Open the mergeSql function through the connectProperties property; Slow SQL record
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000;
    # Merge monitoring data of multiple DruidDataSource
    useGlobalDataSourceStat: true
mybatis-plus:
      mapper-locations: classpath*:/com/gitegg/*/*/mapper/*Mapper.xml
      typeAliasesPackage: com.gitegg.*.*.entity
      global-config:
        #Primary key type 0: "self increment of database ID", 1: "user input ID",2: "globally unique ID (unique ID of digital type)", 3: "globally unique ID UUID";
        id-type: 2
        #Field policy 0: "ignore judgment", 1: "non NULL judgment"), 2: "non empty judgment"
        field-strategy: 2
        #Hump underline conversion
        db-column-underline: true
        #Refresh mapper debug artifact
        refresh-mapper: true
        #Database uppercase underline conversion
        #capital-mode: true
        #Logical delete configuration
        logic-delete-value: 1
        logic-not-delete-value: 0
      configuration:
        map-underscore-to-camel-case: true
        cache-enabled: false

4. You can read the configuration file above. We add the test code to read the configuration in SystemController.java and read a property of the configuration. If you need to read the real-time refresh data, you can add the @ RefreshScope annotation

package com.gitegg.service.system.controller;

import com.gitegg.platform.boot.common.base.Result;
import com.gitegg.platform.boot.common.exception.BusinessException;
import com.gitegg.service.system.dto.SystemDTO;
import com.gitegg.service.system.service.ISystemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping(value = "system")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Api(tags = "gitegg-system")
@RefreshScope
public class SystemController {

    private final ISystemService systemService;

    @Value("${spring.datasource.maxActive}")
    private String nacosMaxActiveType;

    @GetMapping(value = "list")
    @ApiOperation(value = "system list Interface")
    public Object list() {
        return systemService.list();
    }


    @GetMapping(value = "page")
    @ApiOperation(value = "system page Interface")
    public Object page() {
        return systemService.page();
    }

    @GetMapping(value = "exception")
    @ApiOperation(value = "Custom exception and return test interface")
    public Result<string> exception() {
        return Result.data(systemService.exception());
    }

    @PostMapping(value = "valid")
    @ApiOperation(value = "Parameter verification test interface")
    public Result<systemdto> valid(@Valid @RequestBody SystemDTO systemDTO) {
        return Result.data(systemDTO);
    }

    @PostMapping(value = "nacos")
    @ApiOperation(value = "Nacos Read configuration file test interface")
    public Result<string> nacos() {
        return Result.data(nacosMaxActiveType);
    }
}

5. Start the project and open the browser to access: http://127.0.0.1:8001/doc.html , click the Nacos read configuration file test interface menu to test and view the read configuration information. Because @ RefreshScope is added, we test the real-time refresh function, manually modify the spring.datasource.maxActive configuration in Nacos, and execute the test interface again to see that the read configuration information has been refreshed

The source code of this article is in https://gitee.com/wmz1930/GitEgg chapter-10 branch of.

Topics: Spring Cloud Microservices