Chapter 12 Detailed Explanation of Spring Cloud Config Unified Configuration Center

Table of contents

1. Configuration problem analysis and solution

1. Problem Analysis

2. Solutions

2. Introduction to Spring Cloud Config

1, Spring Cloud Config characteristics

2, Spring Cloud Config action    

3. Spring Cloud Config components

   Unified configuration center server

   Unified configuration center client

4. Spring Cloud Config workflow

3. Use of Configuration Center

1 Build a remote git warehouse

1.1 Create a new remote storage

1.2. Create a configuration file for remote warehouse management 

2 Build a unified configuration service center server

2.1 Create a project and introduce dependencies

2.2 Create startup class Add annotation @EnableConfigServer

2.3 Configure remote storage information managed by config Server

2.4 ConfigServer obtains remote configuration information test

3. Build a unified configuration service center client

3.1 Create a project and introduce dependencies

3.2 Order service configuration 

3.3 Create order service controller

3.4 Create a startup class

3.5 Start the test


1. Configuration problem analysis and solution

1. Problem Analysis

        As can be seen from the above figure, each microservice has a configuration file. At present, there are only 11 microservices, and 11 configuration files are needed. What if there are hundreds of microservices? Conventional configuration management solutions are missing the following:

  • Hardcoding (requires code modification, cumbersome, risky)
  • properties or yml (need to be replaced and restarted in a cluster environment)
  • xml (repackage and restart) 

2. Solutions

        Use the centralized configuration management center of Spring Cloud Config to realize the unified management of service configuration in the microservice system.

        Components: The unified configuration center server centrally manages configuration files, and the unified configuration center client is each microservice.

2. Introduction to Spring Cloud Config

1, Spring Cloud Config characteristics

  • Provide server and client support (Spring Cloud Config Server and Spring Cloud Config Client)
  • Centralized management of application deployment in a distributed environment
  • Encryption and decryption of attribute values ​​(symmetric encryption and asymmetric encryption)
  • Based on the Spring environment, seamlessly integrate with Spring applications
  • Programs available for development in any language
  • The default implementation is based on Git, which can perform version management

2, Spring Cloud Config action    

  • Spring Cloud Config centrally manages configuration files
  • Different configurations in different environments, dynamic configuration updates, deployment in different environments such as dev/test/prod/beta/release
  • Dynamically adjust the configuration during operation, no longer need to write configuration files on the machine where each service is deployed, and the service will uniformly pull its own configuration from the configuration center
  • When the configuration changes, the service can sense the configuration change and apply the new configuration without restarting
  • Expose configuration information in the form of REST interface

3. Spring Cloud Config components

        In the microservice distributed system, Spring Cloud Config adopts the components of " Server server " and "Client client" to provide scalable configuration services.

   Unified configuration center server

  • is an independent microservice application
  • Centrally manage configuration files
  • Provides storage for configuration files
  • Provide the content of the configuration file in the form of an interface; 

   Unified configuration center client

  • is each microservice
  • Obtain and load data (configuration information) from the configuration center through the interface at startup
  • And initialize your own application based on this configuration information.

4. Spring Cloud Config workflow

       Workflow: The microservice is config client to config server to obtain the configuration file, and config server to the remote warehouse to obtain the configuration.

       Detailed description: The config Server of the unified configuration center server is also a microservice. This microservice may be a small cluster in the future. If all configurations are placed in the config Server, once the version changes, the entire small cluster needs to be changed. Therefore, the configuration of all microservices can be placed on the git remote warehouse for version management. Config Server only needs to configure the git remote storage address. When config Server starts, config Server will pull the configuration from the git remote storage to the local storage. If the configuration of the remote storage is changed after startup, config Server will automatically detect the configuration change of the remote storage and automatically pull the latest configuration. Other microservices, namely the config client, can obtain the required configuration information through the config server.
Therefore, it is necessary to build a git remote storage environment.

       Note : There are certain rules when the config Server of the unified configuration center server reads the configuration of the remote warehouse, so the naming of configuration files in the remote warehouse also has certain rules.

  • Naming Rules for Remote Storage Configuration Files

       {application}-{profile}.yml/{application}-{profile}.properties

       如:order-dev.yml、order-test.yml、order-prod.yml

  • config Server reads the configuration rules of the remote repository:    

       Among them, the label represents the branch such as the master branch, and the profile represents the environment.

       如:http://localhost:7001/master/order-dev.yml
       如:http://localhost:7001/master/order-test.yml
       如:http://localhost:7001/order/dev/master
       如:http://localhost:7001/order/test/master

3. Use of Configuration Center

       Steps to use the configuration center

  • Build a remote git repository
  • Build a unified configuration service center server
  • Build a unified configuration service center client

1 Build a remote git warehouse

1.1 Create a new remote storage

1.2. Create a configuration file for remote warehouse management 

       Configure the order service on the remote warehouse master branch, and the environments are dev/test/prod. The file names are order-dev.yml, order-test.yml, and order-prod.yml, and the port numbers of the order service are: 9000, 9100, and 9200. The configurations are as follows:

server:
  port: 9000
spring:
  application:
    name: order-service 

# 配置eureka客户端信息
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8000/eureka/
  instance:
    prefer-ip-address: true
    # instance-id: order-service
    instance-id: ${spring.cloud.client.ip-address}:${server.port}

2 Build a unified configuration service center server

2.1 Create a project and introduce dependencies

       Build the config server of the unified configuration service center server, create a project, and introduce the config dependency of the unified service configuration center.

<?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>springcloudbase</artifactId>
        <groupId>com.hwadee.springcloud2022</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>configServer7009</artifactId>

    <dependencies>
        <!-- 添加统一服务配置中心 config-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
        <!--Eureka Client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

</project>

2.2  Create a startup class  and add annotations @EnableConfigServer

       Create a startup class and add the annotation @EnableConfigServer  to start the config server application .

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient// 启动 eureka 客户端
@EnableConfigServer// 启动 config 服务端
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}

2.3  Configure   remote storage information managed by config Server 

       Configure the remote warehouse address to be managed by the server of config  Server .

server:
  port: 7009
spring:
  application:
    name: config-service # 为当前商品服务命名
  cloud:
    config:
      server:
        git:
          #  username: xiashanzhu
          #  password: aa@86886830622
          uri: https://gitee.com/xiashanzhu/config-repo #要读取的远程仓库的配置文件的地址。
          default-label: master # 指定分支,不指定则默认master
eureka:
  client:
    service-url: # 配置服务注册地址,与 eureka-server 中暴露地址保持一致
      defaultZone: http://localhost:8000/eureka
  instance:
    prefer-ip-address: true  # 是否使用 IP 地址注册,默认 false
    # instance-id: product-service  # 实例 id,服务的唯一标识
    instance-id: ${spring.cloud.client.ip-address}:${server.port} # 如果想在控制页面看到服务地址与端口,可以将 instance-id 这样配置
    lease-renewal-interval-in-seconds: 5  # 发送心跳的间隔,单位秒,默认 30
    lease-expiration-duration-in-seconds: 10 # 续约到期时间,单位秒,默认90

2.4 ConfigServer obtains remote configuration information test

           Start the registration center and the config server of the unified configuration center server respectively, and test them respectively according to the rules read from the configuration described above.

  • / label /{ application }-{ profile }.yml mode test

       Test: http://localhost:7001/ master / order- dev.yml Test
       : http://localhost:7001/ master / order - test.yml

  • /{ application }/{ profile }/ label test

       Test: http://localhost:7001/order / dev / master
       Test: http://localhost:7001/order / test / master

 Note:
          
/{ application }-{ profile }.yml accesses the configuration file under the master branch by default. For example visit

          http://localhost:7009/order/dev   and  http://localhost:7009/order/dev/master result the same:

summary

       When the configuration service center server accesses the configuration file of the remote storage, such as http://localhost:7009/order/dev/master , the configuration service center server will automatically pull the remote storage to the local, for example: C:/Users/HP/AppData/Local/Temp/config-repo-xxxx/ directory.

3. Build a unified configuration service center client

3.1 Create a project and introduce dependencies

       Build the config client of the unified configuration service center client, create an order service project, and introduce the spring-cloud-starter-config dependency of the unified service configuration center. It is equivalent to opening the client of the unified configuration service center.

<?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>springcloudbase</artifactId>
        <groupId>com.hwadee.springcloud2022</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.hwadee.springcloud</groupId>
    <artifactId>orderServer9000</artifactId>

    <dependencies>
        <!-- 统一配置服务中心客户端依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <!--动态健康监控 可以用于动态感知配置变化-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!--web依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 管理公共api -->
        <dependency>
            <groupId>com.hwadee.springcloud</groupId>
            <artifactId>springcloud-api</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <!--Eureka Client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- 方便创建类的gettter setter -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

</project>

3.2 Order service configuration 

  • Remote warehouse creation order service configuration 

       Configure the order service on the remote warehouse master branch, and the environments are dev/test/prod. The file names are order-dev.yml, order-test.yml, and order-prod.yml, and the port numbers of the order service are: 9000, 9100, and 9200. The configurations are as follows:.

  • Create order service configuration locally 

       The order service client needs to load the configuration file when it starts, but at this time the configuration file is not in the local, but in the remote warehouse, and an error will be reported when running at this time. Therefore, a local configuration file bootstrap.yml/properties is required during operation, and the client is informed in bootstrap.yml/properties that the configuration file needs to be obtained from the config server . The reason for using the configuration file bootstrap is that the loading order of the bootstrap configuration file has the highest priority when the microservice starts.

There are two ways to obtain the configuration file on the config Server server        in bootstrap.yml/properties  , hard-coded and service name.

       Hardcoded way (not recommended):

       The hard-coded method means that  the address of the config Server server  is hard-coded in the bootstrap. However, it is not recommended, because  the config Server server  is also in cluster mode. If the hard-coded service hangs up, other services will fail. The configuration is as follows:

spring:
  cloud:
    config:
      label: master # 指定分支
      name: order # 指定应用名称
      profile: dev # 指定激活环境
      uri: http://localhost:7009 #硬编码 指定访问 config server 远程仓储的地址的ip和端口

       Service name method:

       Use  the service name method of the config Server server  . Because  the config Server server  is also in cluster mode, using the service name, the order service will first go to the registration center to find the address of the service name of the config Server server  , and then select one of these addresses to obtain the remote configuration file information. But the configuration information of the registration center needs to be written in bootstrap instead of being configured in the remote warehouse.

       The registration center information is modified to:

        The bootstrap.yml configuration information is modified to:

spring:
  cloud:
    config:
      discovery:
        service-id: CONFIG-SERVICE  #告诉当前客户端 统一配置中心的服务端服务id
        enabled: true #开启客户端,根据服务id到注册中心获取配置信息
      label: master # 指定分支
      name: order # 指定应用名称
      profile: dev # 指定激活环境

# 配置eureka客户端信息
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8000/eureka/

3.3 Create order service controller

import com.hwadee.springcloud.entity.Product;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Value("${env}")
    private String env;
    @Value("${port}")
    private String port;
    @Value("${info}")
    private String info;

    @RequestMapping(value = "/getConfig")
    public Product getConfigInfo() {
        Product product = new Product();
        product.setName(env +"环境 端口:"+ port +" "+ info);
        return product;
    }

}

3.4 Create a startup class

      Create a startup class and add the annotation @EnableEurekaClient to the startup class to inject it into the service center in the future.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;


@SpringBootApplication
@EnableEurekaClient// 启动 eureka 客户端
public class OrderServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderServerApplication.class, args);
    }
}

3.5 Start the test

     Start the registration center, configure the management center server, and order services. Test the hardcoded and service name methods respectively.

  • Configuration file hard-coded test:

        Restart the order service, enter the address  http://localhost:9000/order/getConfig   to view the result

  • Configuration file service name mode test:

       Restart the order service, enter the address  http://localhost:9000/order/getConfig   to view the result

Chapter 11: Detailed Explanation of GetAway Service Gateway

Chapter 13: Detailed Explanation of Spring Cloud Config Unified Configuration Center - Client Dynamic Refresh

Guess you like

Origin blog.csdn.net/qq_41946216/article/details/127422810