1. Distributed configuration center

In a distributed system, the number of services increases rapidly, and its configuration files need to be managed in a unified manner and updated in real time. Therefore, a distributed configuration center is necessary. Spring Cloud provides a configuration central component, Spring Cloud Config, which enables configuration services to be placed in remote Git repositories and local files. By default, Git is used to store configuration information, and the example of the author also uses the default Git repository, so that it is convenient to manage and access configuration content through git client tools.

Configure the server schematic diagram

In the Spring Cloud Config component, there are two roles: the Config Server configuration Server, which provides configuration file information for other services; The other is Config Client, which is another service that pulls configuration from Config Server at startup. The following describes the implementation methods of Config Server and Config Client.

2. Configure the Server Config Server

2.1 jars in POM

All you need to do is add references to the following two JAR packages.

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>jsr311-api</artifactId>
                    <groupId>javax.ws.rs</groupId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>Copy the code

Because the Spring Cloud Config server provides configuration for clients through service discovery, consul’s starter is introduced to register both configuration servers and clients with Consul cluster.

2.2 the entry class

Simple, because Spring Cloud provides a lot of out-of-the-box functionality to enable the configuration server with spring-Cloud-config-server annotations.

@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigServer
public class ConfigServerApplication {
    public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); }}Copy the code

The @enableconFigServer annotation is important, marking the service as a configuration server; @enableDiscoveryClient Registers the service for other services to discover and invoke.

2.3 the bootstrap. Yml

server:
  port: 8888

spring:
  application:
    name: config-server
  cloud:
      consul:
        discovery:
          preferIpAddress: true
          enabled: true
          register: true
          service-name: config-service
          / /...
        host: localhost
        port: 8500
---
spring:
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/keets/Config-Repo.git
          searchPaths: ${APP_LOCATE:dev}
          username: user
          password: pwdCopy the code

The first section of the configuration specifies the port for the service. The second section is the configuration related to service discovery; The third section is the configuration server information, where the configuration file is stored on the code cloud. The default path to search for the file is the dev folder, which can be specified by environment variables, followed by the username and password, which are not required for public projects.

So far the configuration server has been set up, isn’t it very simple?

3. Configure the Git repository

The configuration of the server configuration warehouse is https://gitee.com/keets/Config-Repo.git. I created two folders in the repository: dev and Prod. In the dev folder, a new file is created: configclient-dev.yml. Why do you name it that way? Can you name it anything you want? The answer is no. Let’s look at the naming rules for config files.

The mapping between urls and configuration files is as follows:

  • /{application}/{profile}[/{label}]
  • /{application}-{profile}.yml
  • /{label}/{application}-{profile}.yml
  • /{application}-{profile}.properties
  • /{label}/{application}-{profile}.properties

    Yml. {label} corresponds to different branches on Git. The default is master

    For example, Config Client, {application} corresponds toSpring. Application: configclientExp corresponds to {profile}. If {label} is not specified, it defaults to master.

Create configclient-dev.yml as follows:

spring:
  profiles: dev

cloud:
  version: Dalston.SR4Copy the code

4. Configure the Client Config Client

4.1 jars in POM

All you need to do is add references to the following two JAR packages.

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>jsr311-api</artifactId>
                    <groupId>javax.ws.rs</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>Copy the code

Added spring-boot-starter-actuator monitoring module, which contains /refresh API to dynamically refresh configuration information. The others are the same as those added in the configuration server, nothing to say.

4.2 the entry class

Simple, because Spring Cloud provides a lot of out-of-the-box functionality to enable the configuration server with spring-Cloud-config-server annotations.

@SpringBootApplication
@EnableDiscoveryClient
public class ConfigServerApplication {
    public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); }}Copy the code

The @enableconFigServer annotation is not required to configure the client.

4.3 the bootstrap. Yml


server:
  port: 9901
cloud:
  version: Brixton SR7

spring:
  cloud:
    consul:
      discovery:
        preferIpAddress: true
        enabled: true
        register: true
        service-name: config-client
      / /...
      host: localhost
      port: 8500

---
spring:
  profiles:
    active: dev
  application:
      # the name of the app
    name: configclient
  cloud:
    config:
      # specified profile
      profile: dev
      label: master
      discovery:
        enabled: true
        # server name
        service-id: config-service
      enabled: true
      fail-fast: true

---
spring:
  profiles: default
  application:
    name: configclientCopy the code

From the above configuration, we can see that the activated profile is dev, and the configured configuration service is named config-service, specifying that the configuration is pulled from the master branch. Therefore, during the ConfigClient startup, the configClient-dev configuration file is pulled from the configuration server.

4.4 TestResource

I created a TestResource with an API endpoint of/API /test.

    @Value("${cloud.version}")
    private String version;

    @GetMapping("/test")
    public String from(a) {
        return version;
    }Copy the code

Cloud.version you can see in the configuration file above that Brixton SR7 is specified by default, while dalston.sr4 is set by the author in the configuration center.

5. Test results

5.1 Obtaining The Configuration

First, let’s look at the configuration client startup log and see if it really pulled configClient-dev from the configuration server as we configured it.

ccstart

According to the log, it is consistent with the above configuration guess. We further verify from the API provided by the configuration client.

pj

You can see that it is dalston.sr4 and the configuration service is working.

5.2 Dynamically Refreshing Configurations

Spring Cloud Config also enables dynamic configuration updates. Let’s change the cloud.version configuration in Config Repo to Camden SR7 and apply the configuration by refreshing the /refresh endpoint of the Config client. As you can see from the figure below, the result is expected.

rr

This configuration refresh is done manually and can be triggered using Githook. When you commit your code locally to Git, the URL set below is invoked. There are two endpoints you can use:

  • Refresh: Executing /refresh in POST mode refreshes the configuration in env
  • Restart: if the configuration information has been injected into the bean, as a result of the bean is a singleton, not going to load the modified configuration needed by post to perform/restart, also need to configure the endpoints. Restart. Enabled: true.

In the second case, which is time consuming, @refreshScope is an annotation provided by Spring Cloud that refreshes variable values in the bean when refresh is executed. Let’s take a look at the source code.

Convenience annotation to put a @Bean definition in RefreshScope.

Beans annotated this way can be refreshed at runtime and any components that are using them will get a new instance on the next method call, fully initialized and injected with all dependencies.

RefreshScope is a convenient bean annotation that can be added to refresh the bean at run time. Other components that use the bean will get a new instance object initialized the next time they are called.

The Githook Settings page is shown below.

githook

6. Summary

This paper mainly describes the process of setting up the configuration server and the configuration client, and finally verifies whether the configuration service center can be successfully used through the log and endpoint information of the configuration client. In general, it’s pretty simple. Part of the configuration in this article is not complete, the reader needs to see the git project at the end of this article.

However, this article is not complete about configuration center. The next article will explain the combination of configuration server and message bus to achieve automatic update and grayscale publishing functions of configuration client.

In this paper, the source code

github: Github.com/keets2012/S…

gitee: Gitee.com/keets/sprin…

Subscribe to the latest articles, welcome to follow my official account

Wechat official account


reference

  1. Spring Cloud Config
  2. Distributed configuration Center