Simple use of Spring Cloud Config

This article is the summary of the book "Spring Cloud micro service practical war"

quick get start

Build configuration center

  1. Create a basic Spring Boot project and add dependency:
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-config-server</artifactId>
</dependency>
  1. Add @ EnableConfigServer annotation on the main class to enable the server function of Spring Cloud Config

  2. Add configuration information

spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: https://github.com/LiuRunzhi/springcloud_config/ # Location of git warehouse
          search-paths: spring_cloud_config #Configure the relative search location under the warehouse path. You can configure multiple
          username: username #User name to access git warehouse
          password: password #User password to access git warehouse

server:
  port: 7001
  1. Verify that the configuration center is OK

We add configuration files in the warehouse, such as userserver.properties ,userserver- dev.yml , userserver prod, then access the configuration center using the following format:

  • /{application}-{profile}.yml

    http://localhost:7001/userserver-dev.yml

  • /{application}-{profile}.properties

    http://localhost:7001/userserver-dev.properties

We add a config label test branch in Git warehouse, submit configuration to the branch, and then access it in the following format:

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

    http://localhost:7001/userserver/dev/config-label-test

  • /{lable}/{application}-{profile}.yml

    http://localhost:7001/config-label-test/userserver-test.yml

  • /{lable}/{application}-{profile}.properties

    http://localhost:7001/config-label-test/userserver-dev.yml

Access mode without file suffix will return JSON data with configuration information, and access mode with file suffix will directly return configuration information string.

Through the above request, the configuration center temporarily stores the configuration file locally through Git, which can effectively prevent the failure to load the configuration information due to Git warehouse failure. If this happens, the configuration center will return the locally staged configuration information.

Client configuration mapping

  1. Add dependency in microservice application:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
  1. newly build bootstrap.yml configuration file
spring:
 application:
   name: server_client
 cloud:
   config:
     label: master
     profile: test
     uri: http://localhost:7001/

The application will request configuration information from the configuration service according to the above configuration.

  1. Injection configuration information:
@Value("${msg}")
private String msg;
//Or:
@Autowired
private Environment env;

public void test(){
    System.out.println(env.getProperty("msg","undefined"));
}

Server details

Infrastructure

  1. When the app starts, according to the bootstrap.properties The application name {application}, environment name {profile}, and branch name {label} configured in request configuration information from configuration center.

  2. The configuration center looks up the configuration information according to the configuration location information from Git warehouse and client.

  3. Download the found configuration information to the file system in the configuration center through the git clone command.

  4. The configuration center creates the ApplicationContext instance of Spring, loads the configuration information from Git local warehouse, and finally reads the configuration content and returns it to the client application.

  5. After the client application obtains the external configuration file and loads it to the ApplicationContext instance of the client, the repeated configuration information inside the Jar package will be overwritten by the external configuration information.

Git configuration warehouse

For Git remote warehouse address, we can also use {application}, {profile}, {label} placeholders, such as:

spring:
 cloud:
   config:

     uri: http://localhost:7001/{application}

In this way, when the client wants to configure the center to request configuration information, the configuration center can spring.application.name To fill in the {application} placeholder.

In addition, when the branch name of the remote warehouse contains' / ', the {label} parameter should use "(_ )"To replace

Configure multiple warehouses

spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: https://github.com/LiuRunzhi/springcloud_config/
          search-paths: spring_cloud_config
          username: LiuRunZhi
          password: zhi3731182
          repos:
            consumer:
              pattern: consumer/*
              uri: https://gitee.com/zhirun/springcloudconfig/
server:
  port: 7001

In the above configuration, access http://localhost:7001/consumer/test, will read the request https://gitee.com/zhirun/springcloudconfig/consumer-test.yml and https://gitee.com/zhirun/springcloudconfig/consumer-test.properties

safeguard

We can add Spring Security in the configuration center to achieve password protection.

  1. Configuration center join dependency:
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>
  1. Configure user name and password
spring:
 security:
   user:
     name: user
     password: 123456
  1. Add security information to the client to pass the verification:
spring:
  cloud:
    config:
      username: user
      password: 123456

Encryption and decryption

Symmetric encryption

If you are using Oracle JDK, you need to download JCE and replace $Java_ Local under home / JRE / lib / security directory_ policy.jar And US_export_policy.jar Two jar packages, if using OpenJDK, do not need this step.

We need the bootstrap.yml Add secret key information to the configuration file:

encrypt:
    key: AnyStringYouWantOnlyIfTtsComplex

Then we can encrypt and decrypt through / encrypt and / decrypt, both requests are post. If we use Spring Security, we need to turn off csrf for these two requests:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().mvcMatchers(HttpMethod.POST, "/encrypt/**","/decrypt/**").permitAll();
    }
}

Encryption and decryption related endpoint:

  • /encrypt/status: View encryption function status
  • /Key: view the secret key
  • /Encrypt: encrypt the body content of the request
  • /decrypt: body content decryption requested by the team

Profile in remote warehouse:
In the case of an yml profile:

msg: '{cipher}316d12b654c3731cff08ee8c36e26769d4e97d6caa7b78c85949105e5757675d84fdfd78413d9f17ffdb173ffc66c62d'

If it's a properties file (no single quotes required):

msg: {cipher316d12b654c3731cff08ee8c36e26769d4e97d6caa7b78c85949105e5757675d84fdfd78413d9f17ffdb173ffc66c62d

Asymmetric encryption

Use the keytool provided with the JDK to generate the secret key:

Then in the configuration center bootstrap.yml Configuration in profile:

encrypt:
  key-store:
    location: file:///e:\config-server.keystore #If the secret key is in the classpath path, you can directly specify the secret key name, which is config-server.keystore
    alias: config-server
    password: 123456 #Secret key library password
    secret: 123456 #It can't be set randomly, because I didn't ask me to enter the secret key password when generating the key, but only the secret key library password, so the secret key password should be the same as the secret key library password, I guess it should be set here

Service configuration center

  1. Both the configuration center and the client join the eureka dependency

  2. Add @ EnableDiscoveryClient annotation to the main class of configuration center and client

  3. Configuration center's application.yml The service registration center is specified in the configuration file, and the customer list is applied in the bootstrap.yml Registration Center specified in

  4. client bootstrap.yml Make the following configuration:

spring:
 application:
   name: server_client
 cloud:
   config:
     profile: test
     discovery:
       enabled: true #Enable access to the configuration center through services
       service-id: CONFIG-SERVER #Service name registered by configuration center
eureka:
  client:
    service-url:
      defaultZone: http://192.168.1.6:1111/eureka
  instance:
    prefer-ip-address: true

Dynamic refresh configuration

We only need to add actor dependency to the client:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Then expose the / refresh port:

management:
  endpoints:
    web:
      exposure:
        include: refresh

When the configuration of the remote warehouse changes, we can request the client's / Actor / refresh port by Post, so that the configuration information in the client's ApplicationContext can be retrieved and refreshed again.

Tags: Spring git github JDK

Posted on Sat, 27 Jun 2020 23:59:04 -0400 by loveitandhateit