Netflix Archaius with Various Database Configurations – 使用各种数据库配置的Netflix Archaius

最后修改: 2018年 9月 27日

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

 1. Overview

1.概述

The Netflix Archaius offers libraries and functionality for connecting to many data sources.

Netflix Archaius提供了连接许多数据源的库和功能。

In this tutorial, we’ll learn how to get configurations:

在本教程中,我们将学习如何获得配置

  • Using the JDBC API to connect to a database
  • From configurations stored in a DynamoDB instance
  • By configuring Zookeeper as a dynamic distributed configuration

For the introduction to Netflix Archaius, please have a look at this article.

关于Netflix Archaius的介绍,请看看这篇文章

2. Using Netflix Archaius with a JDBC Connection

2.使用Netflix Archaius与JDBC连接

As we explained in the introductory tutorial, whenever we want Archaius to handle the configurations, we’ll need to create an Apache’s AbstractConfiguration bean.

正如我们在介绍性教程中解释的那样,无论何时我们希望Archaius处理配置,我们都需要创建一个Apache的AbstractConfiguration Bean。

The bean will be automatically captured by the Spring Cloud Bridge and added to the Archaius’ Composite Configuration stack.

该bean将被Spring Cloud Bridge自动捕获并添加到Archaius的复合配置栈中。

2.1. Dependencies

2.1. 依赖性

All the functionality required to connect to a database using JDBC is included in the core library, so we won’t need any extra dependency apart from the ones we mentioned in the introductory tutorial:

使用JDBC连接数据库所需的所有功能都包含在核心库中,所以除了我们在介绍性教程中提到的那些功能外,我们不需要任何额外的依赖。

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-archaius</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-netflix</artifactId>
            <version>2.0.1.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

We can check Maven Central to verify we’re using the latest version of the starter library.

我们可以检查Maven Central,以验证我们是否使用了最新版本的starter库

2.2. How to Create the Configuration Bean

2.2.如何创建配置Bean

In this case, we’ll need to create the AbstractConfiguration bean using a JDBCConfigurationSource instance.

在这种情况下,我们需要使用JDBCConfigurationSource实例创建AbstractConfiguration Bean。

To indicate how to obtain the values from the JDBC database, we’ll have to specify:

为了表明如何从JDBC数据库中获取数值,我们必须指定。

  • a javax.sql.Datasource object
  • a SQL query string that will retrieve at least two columns with the configurations’ keys and its corresponding values
  • two columns indicating the properties keys and values, respectively

Let’s go ahead then an create this bean:

那么让我们继续创建这个bean。

@Autowired
DataSource dataSource;

@Bean
public AbstractConfiguration addApplicationPropertiesSource() {
    PolledConfigurationSource source =
      new JDBCConfigurationSource(dataSource,
        "select distinct key, value from properties",
        "key",
        "value");
    return new DynamicConfiguration(source, new FixedDelayPollingScheduler());
}

2.3. Trying It Out

2.3.试用

To keep it simple and still have an operative example, we’ll set up an H2 in-memory database instance with some initial data.

为了保持简单,并且仍然有一个可操作的例子,我们将用一些初始数据建立一个H2内存数据库实例。

To achieve this, we’ll first add the necessary dependencies:

为了实现这一目标,我们首先要添加必要的依赖性。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <version>2.0.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.197</version>
    <scope>runtime</scope>
</dependency>

Note: we can check the latest versions of the h2 and the spring-boot-starter-data-jpa libraries in Maven Central.

注意:我们可以在Maven中心检查h2spring-boot-starter-data-jpa库的最新版本。

Next, we’ll declare the JPA entity that will contain our properties:

接下来,我们将声明JPA实体,它将包含我们的属性。

@Entity
public class Properties {
    @Id
    private String key;
    private String value;
}

And we’ll include a data.sql file in our resources to populate the in-memory database with some initial values:

我们将在我们的资源中包括一个 data.sql文件,以便用一些初始值来填充内存数据库。

insert into properties
values('baeldung.archaius.properties.one', 'one FROM:jdbc_source');

Finally, to check the value of the property at any given point, we can create an endpoint that retrieves the values managed by Archaius:

最后,为了在任何时候检查属性的值,我们可以创建一个端点,检索Archaius管理的值。

@RestController
public class ConfigPropertiesController {

    private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory
      .getInstance()
      .getStringProperty("baeldung.archaius.properties.one", "not found!");

    @GetMapping("/properties-from-dynamic")
    public Map<String, String> getPropertiesFromDynamic() {
        Map<String, String> properties = new HashMap<>();
        properties.put(propertyOneWithDynamic.getName(), propertyOneWithDynamic.get());
        return properties;
    }
}

If the data changes at any point, Archaius will detect it at runtime and will start retrieving the new values.

如果数据在任何时候发生变化,Archaius会在运行时检测到,并开始检索新的数值。

This endpoint can be used in the next examples as well, of course.

当然,这个端点也可以在接下来的例子中使用。

3. How to Create a Configuration Source Using a DynamoDB Instance

3.如何使用DynamoDB实例创建一个配置源

As we did in the last section, we’ll create a fully functional project to analyze properly how Archaius manages properties using a DynamoDB instance as a source of configurations.

正如我们在上一节所做的那样,我们将创建一个功能齐全的项目,以正确分析Archaius如何使用DynamoDB实例作为配置来源来管理属性。

3.1. Dependencies

3.1. 依赖性

Let’s add the following libraries to our pom.xml file:

让我们将以下库添加到我们的pom.xml文件中。

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-dynamodb</artifactId>
    <version>1.11.414</version>
</dependency>
<dependency>
    <groupId>com.github.derjust</groupId>
    <artifactId>spring-data-dynamodb</artifactId>
    <version>5.0.3</version>
</dependency>
<dependency>
    <groupId>com.netflix.archaius</groupId>
    <artifactId>archaius-aws</artifactId>
    <version>0.7.6</version>
</dependency>

We can check Maven Central for the latest dependencies versions, but for the archaius-aws one, we suggest sticking to the version supported by the Spring Cloud Netflix library.

我们可以查看Maven中心的最新依赖版本,但对于archaius-aws一个,我们建议坚持使用Spring Cloud Netflix库支持的版本。

The aws-java-sdk-dynamodb dependency will allow us to set up the DynamoDB client to connect to the database.

aws-java-sdk-dynamodb 依赖将允许我们设置DynamoDB客户端以连接到数据库。

With the spring-data-dynamodb library, we will set up the DynamoDB repository.

通过spring-data-dynamodb库,我们将设置DynamoDB资源库。

And lastly, we’ll use the archaius-aws library to create the AbstractConfiguration.

最后,我们将使用archaius-aws库来创建AbstractConfiguration

3.2. Using DynamoDB as a Configuration Source

3.2.使用DynamoDB作为配置源

This time, the AbstractConfiguration will be created using a DynamoDbConfigurationSource object:

这一次,AbstractConfiguration将使用DynamoDbConfigurationSource对象创建:

@Autowired
AmazonDynamoDB amazonDynamoDb;

@Bean
public AbstractConfiguration addApplicationPropertiesSource() {
    PolledConfigurationSource source = new DynamoDbConfigurationSource(amazonDynamoDb);
    return new DynamicConfiguration(
      source, new FixedDelayPollingScheduler());
}

By default Archaius searches for a table named ‘archaiusProperties’, containing a ‘key’ and a ‘value’ attributes in the Dynamo database to use as a source.

默认情况下,Archaius会在Dynamo数据库中搜索一个名为 “archaiusProperties “的表,其中包含一个 “key “和一个 “value “属性,以作为数据源。

If we want to override those values, we’ll have to declare the following system properties:

如果我们想覆盖这些值,我们就必须声明以下系统属性。

  • com.netflix.config.dynamo.tableName
  • com.netflix.config.dynamo.keyAttributeName
  • com.netflix.config.dynamo.valueAttributeName

3.3. Creating a Fully Functional Example

3.3.创建一个全功能的例子

As we did in this DynamoDB guide, we’ll start by installing a local DynamoDB instance to test the functionality easily.

正如我们在本DynamoDB指南中所做的那样,我们将首先安装一个本地DynamoDB实例,以便轻松测试功能。

We’ll also follow the instructions of the guide to create the AmazonDynamoDB instance that we ‘autowired’ previously.

我们还将按照指南的指示,创建我们之前 “自动连接 “的AmazonDynamoDB实例。

And to populate the database with some initial data, we’ll first create a DynamoDBTable entity to map the data:

为了用一些初始数据填充数据库,我们将首先创建一个DynamoDBTable实体来映射数据。

@DynamoDBTable(tableName = "archaiusProperties")
public class ArchaiusProperties {

    @DynamoDBHashKey
    @DynamoDBAttribute
    private String key;

    @DynamoDBAttribute
    private String value;

    // ...getters and setters...
}

Next, we’ll create a CrudRepository for this entity:

接下来,我们将为这个实体创建一个CrudRepository

public interface ArchaiusPropertiesRepository extends CrudRepository<ArchaiusProperties, String> {}

And finally, we’ll use the repository and the AmazonDynamoDB instance to create the table and insert the data afterward:

最后,我们将使用存储库和AmazonDynamoDB实例来创建表并在之后插入数据。

@Autowired
private ArchaiusPropertiesRepository repository;

@Autowired
AmazonDynamoDB amazonDynamoDb;

private void initDatabase() {
    DynamoDBMapper mapper = new DynamoDBMapper(amazonDynamoDb);
    CreateTableRequest tableRequest = mapper
      .generateCreateTableRequest(ArchaiusProperties.class);
    tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L));
    TableUtils.createTableIfNotExists(amazonDynamoDb, tableRequest);

    ArchaiusProperties property = new ArchaiusProperties("baeldung.archaius.properties.one", "one FROM:dynamoDB");
    repository.save(property);
}

We can call this method right before creating the DynamoDbConfigurationSource.

我们可以在创建DynamoDbConfigurationSource之前调用这个方法。

We’re all set now to run the application.

我们现在都准备好了,可以运行该应用程序了。

4. How to Set up a Dynamic Zookeeper Distributed Configuration

4.如何设置动态Zookeeper分布式配置

As we’ve seen before on out introductory Zookeeper article, one of the benefits of this tool is the possibility of using it as a distributed configuration store.

正如我们之前在介绍Zookeeper的文章上看到的那样,这个工具的好处之一是可以将其用作分布式配置存储。

If we combine it with Archaius, we end up with a flexible and scalable solution for configuration management.

如果我们把它和Archaius结合起来,我们最终会得到一个灵活和可扩展的配置管理解决方案。

4.1. Dependencies

4.1. 依赖性

Let’s follow the official Spring Cloud’s instructions to set up the more stable version of Apache’s Zookeeper.

让我们按照Spring Cloud的官方说明来设置Apache的Zookeeper的更稳定版本。

The only difference is that we only need a part of the functionality provided by Zookeeper, thus we can use the spring-cloud-starter-zookeeper-config dependency instead of the one used in the official guide:

唯一的区别是,我们只需要Zookeeper提供的部分功能,因此我们可以使用spring-cloud-starter-zookeeper-config依赖,而不是官方指南中使用的依赖。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zookeeper-config</artifactId>
    <version>2.0.0.RELEASE</version>
    <exclusions>
        <exclusion>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.4.13</version>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Again, we can check the latest versions of spring-cloud-starter-zookeeper-config and zookeeper dependencies in Maven Central.

同样,我们可以在Maven中心检查spring-cloud-starter-zookeeper-configzookeeper的最新版本依赖。

Please make sure to avoid the zookeeper beta versions.

请确保避免使用zookeeper测试版本。

4.2. Spring Cloud’s Automatic Configuration

4.2.Spring Cloud的自动配置

As it’s explained in the official documentation, including the spring-cloud-starter-zookeeper-config dependency is enough to set up the Zookeeper property sources.

正如官方文档中所解释的,包括spring-cloud-starter-zookeeper-config依赖性就足以设置Zookeeper属性源。

By default, only one source is autoconfigured, searching properties under the config/application Zookeeper node. This node is therefore used as a shared configuration source between different applications.

默认情况下,只有一个源是自动配置的,在config/application Zookeeper节点下搜索属性。因此,这个节点被用作不同应用程序之间的共享配置源。

Additionally, if we specify an application name using the spring.application.name property, another source is configured automatically, this time searching properties in the config/<app_name> node.

此外,如果我们使用spring.application.name属性指定一个应用程序名称,就会自动配置另一个源,这次是在config/<app_name>节点中搜索属性。

Each node name under these parent nodes will indicate a property key, and their data will be the property value.

这些父节点下的每个节点名称将表示一个属性键,其数据将是属性值。

Luckily for us, since Spring Cloud adds these property sources to the context, Archaius manages them automatically. There is no need to create an AbstractConfiguration programmatically.

幸运的是,由于Spring Cloud将这些属性源添加到上下文中,Archaius会自动管理它们。不需要以编程方式创建一个AbstractConfiguration。

4.3. Preparing the Initial Data

4.3.准备初始数据

In this case, we’ll also need a local Zookeeper server to store the configurations as nodes. We can follow this Apache’s guide to set up a standalone server that runs on port 2181.

在这种情况下,我们还需要一个本地的Zookeeper服务器来将配置存储为节点。我们可以按照这个Apache的指南来设置一个独立的服务器,在2181端口上运行。

To connect to the Zookeeper service and create some initial data, we’ll use the Apache’s Curator client:

为了连接到Zookeeper服务并创建一些初始数据,我们将使用Apache的Curator客户端

@Component
public class ZookeeperConfigsInitializer {

    @Autowired
    CuratorFramework client;

    @EventListener
    public void appReady(ApplicationReadyEvent event) throws Exception {
        createBaseNodes();
        if (client.checkExists().forPath("/config/application/baeldung.archaius.properties.one") == null) {
            client.create()
              .forPath("/config/application/baeldung.archaius.properties.one",
              "one FROM:zookeeper".getBytes());
        } else {
            client.setData()
              .forPath("/config/application/baeldung.archaius.properties.one",
              "one FROM:zookeeper".getBytes());
        }
    }

    private void createBaseNodes() throws Exception {
        if (client.checkExists().forPath("/config") == null) {
            client.create().forPath("/config");
        }
        if (client.checkExists().forPath("/config/application") == null) {
            client.create().forPath("/config/application");
        }
    }
}

We can check the logs to see the property sources to verify that Netflix Archaius refreshed the properties once they change.

我们可以检查日志,查看属性来源,以验证Netflix Archaius在属性改变后是否刷新了属性。

5. Conclusion

5.总结

In this article, we’ve learned how we can setup advanced configuration sources using Netflix Archaius. We have to take into consideration that it supports other sources as well, such as Etcd, Typesafe, AWS S3 files, and JClouds.

在这篇文章中,我们已经学会了如何使用Netflix Archaius设置高级配置源。我们必须考虑到,它也支持其他来源,如Etcd、Typesafe、AWS S3文件和JClouds。

As always, we can check out all the examples in our Github repo.

一如既往,我们可以在我们的Github repo中查看所有的例子。