Using Spring Cloud Config Without Git – 在没有Git的情况下使用Spring Cloud配置

最后修改: 2022年 2月 17日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

Spring Cloud Config is a library that makes it easy to externalize configuration for Spring applications. It allows us to expose configuration data as a service, making it easy to ingest from any other application that has an HTTP client.

Spring Cloud Config是一个库,可以使Spring应用程序的配置轻松地外部化。它允许我们将配置数据作为一项服务公开,从而使我们能够轻松地从任何其他具有HTTP客户端的应用程序中摄取配置。

In this tutorial, we will look at how to use Spring Cloud Config without git.

在本教程中,我们将看看如何在没有git的情况下使用Spring Cloud Config。

2. Spring Cloud Config Overview

2.Spring Cloud配置概述

The Spring Cloud Config library is a typical client-server model. A centralized server (or servers) reads in configuration data from some external data source. These servers expose various HTTP endpoints that allow any other application to query for configuration data.

Spring Cloud Config库是一个典型的客户-服务器模型。一个集中的服务器(或多个服务器)从一些外部数据源中读入配置数据。这些服务器暴露了各种HTTP端点,允许任何其他应用程序查询配置数据。

spring cloud config overview

Spring Cloud Config Overview

Spring云配置概述

spring cloud config overview

Spring云配置概览

Spring Cloud Config also makes it very easy to connect from a Spring Boot application to a config server automatically. The configuration data that is provided by the server can then be used just like any other properties source inside the client application.

Spring Cloud Config还使自动从Spring Boot应用程序连接到配置服务器变得非常容易。服务器提供的配置数据可以像客户端应用程序中的任何其他属性源一样使用

3. Git Providers

3.Git供应商

The most common use case for Spring Cloud Config is to store configuration data inside a git repository. This type of setup has several advantages:

Spring Cloud Config最常见的用例是在git仓库内存储配置数据。这种类型的设置有几个优点。

  • Flexibility: A git repository can hold various file types, including binary.
  • Security: Easy to control both read and write access at a granular level.
  • Auditing: Robust history tracking allows easy auditing of configuration changes.
  • Standardized: Git operations are standard regardless of provider, meaning we can self-host or use any number of 3rd party providers.
  • Distributed: Git is designed from the ground up to be distributed, so it’s a great fit for cloud-native and microservice architectures.

Despite all the benefits listed above, however, git may not always be the best choice for storing configuration data. For example, our organization may already put configuration data in another data store like a relational database. In this case, it may not be worth the effort to migrate it to git.

尽管有上面列出的所有好处,然而,git不一定是存储配置数据的最佳选择。例如,我们的组织可能已经把配置数据放在另一个数据存储中,如关系型数据库。在这种情况下,可能不值得将其迁移到git上。

In the next section, we’ll take a closer look at using Spring Cloud Config without git.

在下一节,我们将仔细研究在没有git的情况下使用Spring Cloud Config。

4. Using Spring Cloud Config Without Git

4.在没有Git的情况下使用Spring Cloud配置

When we talk about using something other than git with Spring Cloud Config, we are really referring to the server component. Our choice of data store does not impact the client component. Only the server is impacted.

当我们谈到在Spring Cloud Config中使用git以外的东西时,我们实际上是指服务器组件。我们对数据存储的选择并不影响客户端组件。只有服务器会受到影响。

Inside the Spring Cloud Config Server library, there’s a single interface named EnvironmentRepository that defines a configuration source. All configuration sources, both git and otherwise, must implement this interface.

在Spring Cloud Config Server库中,有一个名为EnvironmentRepository的接口定义了一个配置源。所有的配置源,无论是git还是其他,都必须实现这个接口

Let’s look at some of the provided implementations.

让我们来看看一些提供的实现方式。

3.1. File System

3.1 文件系统

Spring Cloud Config provides support for using a file system as a configuration source. To enable this feature, we have to specify the following value in the config server’s application.properties file:

Spring Cloud Config提供了对使用文件系统作为配置源的支持。要启用这一功能,我们必须在配置服务器的application.properties文件中指定以下值。

spring.cloud.config.server.native.search-locations=resources/other.properties

By default, the search location assumes a classpath resource. If we want to use any arbitrary file, we simply include a file resource prefix:

默认情况下,搜索位置假设为classpath资源。如果我们想使用任何任意的文件,我们只需包括一个文件资源前缀。

spring.cloud.config.server.native.search-locations=file:///external/path/other.properties

In addition to this property, the config server needs to run with the native profile enabled:

除了这个属性外,配置服务器需要在启用本地配置文件的情况下运行。

-Dspring.profiles.active=native

It’s important to remember that when using a file system configuration source, we need to ensure the file system is available everywhere the config server will run. This likely means using a distributed file system such as NFS.

重要的是要记住,当使用文件系统配置源时,我们需要确保文件系统在配置服务器将运行的任何地方都是可用的。这可能意味着使用一个分布式文件系统,如NFS。

3.2. JDBC

3.2 JDBC

Spring Cloud Config can also use a relational database to load configuration data using JDBC. This is accomplished via the JdbcEnvironmentRepository class. To enable this class, we have to follow a few steps.

Spring Cloud Config 还可以使用关系型数据库来使用JDBC加载配置数据。这是通过JdbcEnvironmentRepository类完成的。要启用这个类,我们必须遵循几个步骤。

First, the spring-jdbc library must be present on the classpath. If we’re already using Spring Data JDBC or another dependent library, it will already be present. Otherwise, we can always specify it manually:

首先,spring-jdbc库必须存在于classpath中。如果我们已经在使用Spring Data JDBC或其他依赖性库,那么它就已经存在了。否则,我们总是可以手动指定它。

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
</dependency>

Second, we need to specify how to connect to the database:

第二,我们需要指定如何连接到数据库。

spring.datasource.url=jdbc:mysql://dbhost:3306/springconfig
spring.datasource.username=dbuser
spring.datasource.password=dbpassword
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

In this case, we’re using MySQL, but any JDBC-compliant driver will work.

在本例中,我们使用的是MySQL,但任何符合JDBC标准的驱动程序都可以工作。

Next, the database must include a table named PROPERTIES that has the following columns:

接下来,数据库必须包括一个名为PROPERTIES的表,该表有以下列。

  • APPLICATION
  • PROFILE
  • LABEL
  • KEY
  • VALUE

And finally, we need to specify the JDBC profile for the config server:

最后,我们需要为配置服务器指定JDBC配置文件。

-Dspring.profiles.active=jdbc

3.3. Redis

3.3. Redis

Spring Cloud Config also supports Redis as a configuration source. This is accomplished using the RedisEnvironmentRepository class. Similar to the JDBC source, we need to follow a few steps to enable it.

Spring Cloud Config 还支持将 Redis 作为配置源。这可以通过RedisEnvironmentRepository类来实现。与JDBC源类似,我们需要遵循几个步骤来启用它。

First, we need to add a dependency to Spring Data Redis:

首先,我们需要向Spring Data Redis添加一个依赖关系。

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
</dependency>

Second, we need to set some properties for how to connect to Redis:

第二,我们需要为如何连接到Redis设置一些属性。

spring.redis.host=localhost
spring.redis.port=6379

Next, we have to ensure our properties are stored properly in Redis. We can use the HMSET command to store some sample properties:

接下来,我们必须确保我们的属性被正确地存储在Redis中。我们可以使用HMSET命令来存储一些示例属性。

HMSET application sample.property.name1 "somevalue" sample.property.name2 "anothervalue"

If we were to echo back these properties, we should see the following data:

如果我们要回传这些属性,我们应该看到以下数据。

HGETALL application
{
    "sample.property.name1": "somevalue",
    "sample.property.name2": "anothervalue"
}

Finally, we must enable the Redis profile for our Spring Cloud Config server:

最后,我们必须为我们的Spring Cloud Config服务器启用Redis配置文件。

-Dspring.profiles.active=redis

Using Redis as a configuration source also supports different profiles. To do this, we simply add the profile name to the end of the application:

使用Redis作为配置源也支持不同的配置文件。要做到这一点,我们只需在应用程序的末尾添加配置文件的名称。

HMSET application-dev sample.property.name1 "somevalue" sample.property.name2 "anothervalue"

In this example, we’re creating a new set of properties under a profile named dev.

在这个例子中,我们要在一个名为dev的配置文件下创建一组新的属性。

3.4. Secrets

3.4.秘密

A popular feature of many cloud providers is secrets. Secrets allow us to securely store sensitive data as part of our cloud infrastructure. These are perfect for things like usernames, hostnames, and passwords, which we would want to include as part of our application configuration.

许多云提供商的一个流行功能是secretssecrets允许我们安全地存储敏感数据,作为我们云基础设施的一部分。这些数据非常适合用于诸如用户名、主机名和密码,我们希望将其作为应用程序配置的一部分。

Spring Cloud Config provides support for many different cloud secret providers. Below, we’ll look at AWS, which uses the AwsSecretsManagerEnvironmentRepository class to load AWS secrets into a property source.

Spring Cloud Config为许多不同的云秘密提供者提供支持。下面,我们来看看AWS,它使用AwsSecretsManagerEnvironmentRepository类来将AWS的秘密加载到一个属性源。

This class relies on the AWSSecretsManager class to do the heavy lifting of communicating with AWS. While we could manually create it ourselves, the more straightforward solution is to use a Spring starter:

这个类依赖于AWSSecretsManager类来完成与AWS通信的重任。虽然我们可以自己手动创建它,但更直接的解决方案是使用Spring启动器

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-aws-secrets-manager-config</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>

This module includes an auto-configuration that will create an instance of AWSSecretsManager for us. All we have to do is specify a set of properties in our bootstrap.yml file:

这个模块包括一个自动配置,将为我们创建一个AWSSecretsManager的实例。我们所要做的就是在我们的bootstrap.yml文件中指定一组属性。

aws:
  secretsmanager:
    default-context: application
    prefix: /config
    profile-separator: _
    fail-fast: true
    name: ConfigServerApplication
    enabled: true

Now, let’s suppose we want to store our database credentials in a secret and make them available to the config server. We would simply create a new secret at the path /config/application/database_credentials. Inside, we would store the necessary key/value pairs required to connect to the database.

现在,让我们假设我们想把我们的数据库凭证存储在一个秘密中,并让它们对配置服务器可用。我们将简单地在/config/application/database_credentials路径下创建一个新的秘密。在里面,我们将存储连接到数据库所需的必要键/值对。

This construct also supports different profiles. For example, if we have a development database server, we could also create a separate secret for it. We would name it /config/application/database_credentials_dev.

这种结构也支持不同的配置文件。例如,如果我们有一个开发数据库服务器,我们也可以为它创建一个单独的秘密。我们将把它命名为/config/application/database_credentials_dev.

3.5. S3

3.5. S3

Another convenient way to store configuration is with cloud file services. Let’s take a look at how we can use AWS S3 as a configuration source.

另一种存储配置的便捷方式是使用云文件服务。让我们来看看我们如何使用AWS S3作为配置源。

First, we need to add the AWS SDK to our project:

首先,我们需要将AWS SDK添加到我们的项目中。

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-s3outposts</artifactId>
    <version>1.12.150</version>
</dependency>

Then, we need to provide some values to configure a connection to the S3 bucket that contains our property files:

然后,我们需要提供一些值来配置与包含我们属性文件的S3桶的连接。

amazon.s3.access-key=key
amazon.s3.secret-key=secret

And, we’ll need to supply specific properties for the AWS S3 configuration provider:

而且,我们需要为AWS S3配置提供者提供特定的属性。

spring:
  cloud:
    config:
      server:
        awss3:
          region: us-east-1
          bucket: config-bucket

We also need to set a profile to ensure the AWS S3 configuration source is loaded:

我们还需要设置一个配置文件,以确保AWS S3配置源被加载。

-Dspring.profiles.active=awss3

All that’s left is to create our desired property files, including any profile-specific files, inside the bucket. Note that when an application doesn’t have a profile, the config server assumes default. Therefore, we should include a file with this suffix along with any other files that contain specific profile names.

剩下的就是在桶内创建我们想要的属性文件,包括任何配置文件的特定文件。请注意,当一个应用程序没有配置文件时,配置服务器会假定default。因此,我们应该包括一个带有这个后缀的文件,以及任何其他包含特定配置文件名称的文件

3.6. Custom Configuration Source

3.6.自定义配置源

If any of the provided configuration sources don’t meet our needs, we always have the option of implementing our own. In general, this involves creating a new class that implements both EnvironmentRepository and Ordered:

如果所提供的任何配置源不能满足我们的需要,我们总是可以选择实现我们自己的配置。一般来说,这涉及到创建一个新的类,实现EnvironmentRepositoryOrdered

public class CustomConfigurationRepository implements EnvironmentRepository, Ordered {
    @Override
    public Environment findOne(String application, String profile, String label) {
        // Return a new Environment that is populated from
        // our desired source (DB, NoSQL store, etc)
    }

    @Override
    public int getOrder() {
        // Define our order relative to other configuration repositories
        return 0;
    }
}

Then, we simply instantiate this class as a new Spring bean:

然后,我们简单地将这个类实例化为一个新的Spring Bean。

@Bean
public CustomConfigurationRepository customConfigurationRepository() {
    return new CustomConfigurationRepository();
}

4. Multiple Configuration Sources

4.多个配置源

In some cases, it may be necessary to run Spring Cloud Config with multiple configuration sources. In this case, we have to specify a couple of pieces of data.

在某些情况下,可能需要用多个配置源运行Spring Cloud Config。在这种情况下,我们必须指定几条数据。

Let’s say we want to run with both JDBC and Redis as configuration sources. The first thing we need to do is define the order of each source in our bootstrap.yml file:

假设我们想用JDBC和Redis作为配置源运行。我们需要做的第一件事是在bootstrap.yml文件中定义每个来源的顺序。

spring:
  cloud:
    config:
      server:
        redis:
          order: 2
        jdbc:
          order: 1

This allows us to specify the precedence for which configuration sources should be used before others. Because the ordering follows the normal Spring Ordered annotation processing, lower number sources will be checked first.

这允许我们指定哪些配置源应在其他配置源之前使用的优先顺序。因为排序遵循正常的Spring Ordered注解处理,数量较少的来源将被首先检查

Additionally, we need to define both profiles for the server:

此外,我们需要为服务器定义两个配置文件。

-Dspring.profiles.active=jdbc,redis

Note that we could specify the active profiles in the YAML as well. And, this same pattern could be used to define any number of configuration sources.

请注意,我们也可以在YAML中指定活动的配置文件。而且,这种相同的模式可以用来定义任何数量的配置源

5. Conclusion

5.总结

In this article, we’ve covered various configuration sources that can be used with Spring Cloud Config. While git is a great default source for many projects, it may not always be the best choice. We have seen that Spring Cloud Config provides multiple alternatives, as well as the ability to create custom providers.

在这篇文章中,我们已经介绍了可用于Spring Cloud Config的各种配置源。虽然git是许多项目的默认源,但它不一定是最佳选择。我们已经看到,Spring Cloud Config提供了多种选择,以及创建自定义提供者的能力。