Spring Cloud Alibaba - 17 Nacos Config configuration center application

Article catalogue

Basic concept of Nacos configuration center

https://nacos.io/zh-cn/docs/concepts.html

In the process of system development, some parameters and variables that need to be changed are usually separated from the code and managed independently in the form of independent configuration files. The purpose is to make the static system artifacts or deliverables (such as WAR, JAR package, etc.) better adapt to the actual physical running environment. Configuration management is generally included in the process of system deployment, which is completed by the system administrator or operation and maintenance personnel. Configuration change is one of the effective means to adjust the behavior of the system.

Configuration service

A service provider that provides dynamic configuration or metadata and configuration management during the operation of a service or application.

Configuration management

All version management, configuration change management, and configuration related data in the audit center.

Configuration item

A specific configurable parameter and its value range usually exist in the form of param key = param value. For example, we often configure the log output level of the system (logLevel=INFO|WARN|ERROR) as a configuration item.

config set

A set of related or unrelated configuration items is called a configuration set. In the system, a configuration file is usually a configuration set, which contains the configuration of all aspects of the system. For example, a configuration set may contain configuration items such as data source, thread pool and log level.

Configuration set ID

ID of a configuration set in Nacos. Configuration set ID is one of the dimensions of organization partition configuration. Data ID is usually used to organize and partition the configuration set of the system. A system or application can contain multiple configuration sets, and each configuration set can be identified by a meaningful name. Data ID usually adopts the naming rules of Java like package (such as com.taobao.tc.found.log.level) to ensure global uniqueness. This naming rule is not mandatory.

Configure grouping

A set of configuration sets in Nacos is one of the dimensions of organization configuration. Configuration sets are grouped by a meaningful string, such as Buy or Trade, to distinguish configuration sets with the same Data ID. When you create a configuration on Nacos, if the name of the configuration group is not filled in, the name of the configuration group adopts default by DEFAULT_GROUP . Common scenarios of configuration grouping: different applications or components use the same configuration type, such as database_url configuration and MQ_topic configuration.

Configure snapshot

The client SDK of Nacos will generate a snapshot of the configuration locally. When the client cannot connect to the Nacos Server, you can use the configuration snapshot to display the overall disaster recovery capability of the system. The configuration snapshot is similar to the local commit in Git and the cache. It will be updated at the appropriate time, but there is no concept of cache expiration.

Core functions of configuration center

  • Different configurations in different environments
  • Configure property dynamic refresh

Problems to be solved in the implementation of configuration center

Let's look at the figure above. There are several problems to be solved

  • How does the microservice know the address of the configuration center?
  • Which environment does microservice need to connect to?
  • How to find the corresponding configuration file on nacos config?

Microservice access configuration steps

Let's create a project, artist cloud Nacos config, assuming that the project needs to pull the configuration from the configuration center.

(don't be confused by the name of this project. In fact, it is our ordinary micro services, such as ORDER and PRODUCT services, which need to be connected to the configuration)

Step1 dependency package

        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-alibaba-nacos-discoveryartifactId>
        dependency>

        
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-alibaba-nacos-configartifactId>
        dependency>

Step 2 configuration file

To write a configuration file, you need to write a bootstrap YML profile

spring:
  cloud:
    nacos:
      config:  # This is config, and the place of service registration is discovery
        server-addr: 1.117.97.88:8848
        file-extension: yml
  application:  # Indicates that the current microservice needs to ask for the configuration of the artist config center from the configuration center
    name: artisan-config-center
  profiles: # Indicates that I need to ask the configuration center for the development environment configuration of the artist config center
    active: dev
  • Server addr: 1.117.97.88:8848 indicates how my micro service can find my configuration center
  • spring. application. Name = artist config center means that the current micro service needs to ask the configuration center for the configuration of artist config center
  • spring.profiles.active=dev means I need to ask the configuration center for the dev environment configuration of the artist config center

The format of the requested file is

  ${application.name}- ${spring.profiles.active}.${file-extension}

Similarly, our service should also register with Nacos

Step3 Nacos Config add configuration

New configuration

Step4 verification

Start the service and observe the log

2022-02-04 12:37:50.945  INFO 14772 --- [           main] c.a.c.n.c.NacosPropertySourceBuilder     : Loading nacos data, dataId: 'artisan-config-center-dev.yml', group: 'DEFAULT_GROUP', data: server:
    port: 5678
2022-02-04 12:37:50.948  INFO 14772 --- [           main] b.c.PropertySourceBootstrapConfiguration : Located property source: CompositePropertySource {name='NACOS', propertySources=[NacosPropertySource {name='artisan-config-center-dev.yml'}, NacosPropertySource {name='artisan-config-center.yml'}, NacosPropertySource {name='artisan-config-center'}]}

Another chestnut (new value effective without shutdown)

Business scenario

We have a new business online. The business needs to keep the code of the old logic. So we plan to make a switch to isNewPath to control it. In case of any bug after the new function is put into production, how can we modify the isNewBusi value without restarting?

Step1 Nacos Config new configuration item

Based on the previous project, let's add this function

Step 2 @ value resolves the corresponding value

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RefreshScope
@Slf4j
public class OrderInfoController {


    @Value("${isNewPath}")
    private Boolean isNewPath;


    @RequestMapping("/selectOrderInfoById/{orderNo}")
    public Object selectOrderInfoById(@PathVariable("orderNo") String orderNo) {

        log.info("New business logic:{}", isNewPath);
        if (isNewPath) {
            return "Query new logic of order execution->execute new logic : " + orderNo;
        }
        return "Query the old logic of order execution->execute old logic : " + orderNo;

    }

}

Step3 add @ RefreshScope to the controller for dynamic refresh

Step4 verification

Start the service and observe the configuration items of the pulled configuration center

2022-02-04 13:30:27.453  INFO 21040 --- [           main] c.a.c.n.c.NacosPropertySourceBuilder     : Loading nacos data, dataId: 'artisan-config-center-dev.yml', group: 'DEFAULT_GROUP', data: server:
    port: 5678
# Whether to take the switch of new business logic
isNewPath: true     

We can see that it is true. Visit and try it

Modify the value on Nacos Config to false, observe the log and retest

Check the application log

2022-02-04 13:32:29.234  INFO 21040 --- [.117.97.88_8848] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2022-02-04 13:32:29.273  INFO 21040 --- [.117.97.88_8848] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$de53a9bf] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2022-02-04 13:32:30.791  INFO 21040 --- [.117.97.88_8848] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2022-02-04 13:32:30.884  WARN 21040 --- [.117.97.88_8848] c.a.c.n.c.NacosPropertySourceBuilder     : Ignore the empty nacos configuration and get it based on dataId[artisan-config-center] & group[DEFAULT_GROUP]
2022-02-04 13:32:30.952  WARN 21040 --- [.117.97.88_8848] c.a.c.n.c.NacosPropertySourceBuilder     : Ignore the empty nacos configuration and get it based on dataId[artisan-config-center.yml] & group[DEFAULT_GROUP]
2022-02-04 13:32:31.012  INFO 21040 --- [.117.97.88_8848] c.a.c.n.c.NacosPropertySourceBuilder     : Loading nacos data, dataId: 'artisan-config-center-dev.yml', group: 'DEFAULT_GROUP', data: server:
    port: 5678
# Whether to take the switch of new business logic
isNewPath: false     
2022-02-04 13:32:31.013  INFO 21040 --- [.117.97.88_8848] b.c.PropertySourceBootstrapConfiguration : Located property source: CompositePropertySource {name='NACOS', propertySources=[NacosPropertySource {name='artisan-config-center-dev.yml'}, NacosPropertySource {name='artisan-config-center.yml'}, NacosPropertySource {name='artisan-config-center'}]}
2022-02-04 13:32:31.014  INFO 21040 --- [.117.97.88_8848] o.s.boot.SpringApplication               : The following profiles are active: dev
2022-02-04 13:32:31.023  INFO 21040 --- [.117.97.88_8848] o.s.boot.SpringApplication               : Started application in 3.29 seconds (JVM running for 128.768)
2022-02-04 13:32:31.040  INFO 21040 --- [.117.97.88_8848] o.s.c.e.event.RefreshEventListener       : Refresh keys changed: [isNewPath]

The latest value has been obtained, isNewPath: false, and Refresh keys changed: [isNewPath]

We don't restart the application and access it directly

Eh, the old logic goes without stopping

Source code

https://github.com/yangshangwei/SpringCloudAlibabMaster

Added by Shibbey on Sat, 05 Feb 2022 10:45:27 +0200