Introduction to Netflix Archaius with Spring Cloud – 使用Spring Cloud的Netflix Archaius简介

最后修改: 2018年 8月 20日

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

1. Overview

1.概述

Netflix Archaius is a powerful configuration management library.

Netflix Archaius是一个强大的配置管理库。

Simply put, it’s a framework that can be used to gather configuration properties from many different sources, offering fast, thread-safe access to them.

简单地说,它是一个框架,可以用来从许多不同的来源收集配置属性,提供快速、线程安全的访问。

On top of this, the library allows properties to change dynamically at runtime, making it possible for the system to get these variations without having to restart the application.

在此基础上,该库允许属性在运行时动态变化,使系统有可能获得这些变化而不必重新启动应用程序。

In this introductory tutorial, we’ll set up a simple Spring Cloud Archaius configuration, we’ll explain what’s happening under the hood, and finally, we’ll see how Spring allows extending the basic setup.

在这个入门教程中,我们将设置一个简单的Spring Cloud Archaius配置,我们将解释在引擎盖下发生了什么,最后,我们将看到Spring如何允许扩展基本设置。

2. Netflix Archaius Features

2.Netflix Archaius的特点

As we know, Spring Boot already provides instruments to manage externalized configurations, so why bother setting up a different mechanism?

正如我们所知,Spring Boot已经提供了管理外部配置的工具,那么为什么还要麻烦地设置一个不同的机制呢?

Well, Archaius offers some handy and interesting features that aren’t contemplated by any other configuration framework. Some of its key points are:

好吧,Archaius提供了一些其他配置框架没有考虑到的方便和有趣的功能。它的一些关键点是。

  • Dynamic and Typed properties
  • A Callback mechanism that gets invoked on property mutations
  • Ready for use implementations of dynamic configuration sources such as URLs, JDBC and Amazon DynamoDB
  • A JMX MBean that can be accessed by Spring Boot Actuator or JConsole to inspect and manipulate the properties
  • Dynamic properties validation

These perks can be beneficial in many scenarios.

这些福利在许多情况下都是有益的。

Therefore, Spring Cloud has worked on a library that allows to easily configure a ‘Spring Environment Bridge’ so that Archaius can read properties from the Spring Environment.

因此,Spring Cloud已经开发了一个库,允许轻松配置 “Spring环境桥”,这样Archaius就可以从Spring环境中读取属性。

3. Dependencies

3.依赖性

Let’s add the spring-cloud-starter-netflix-archaius to our application, it’ll add all the necessary dependencies to our project.

让我们把spring-cloud-starter-netflix-archaius添加到我们的应用程序中,它将向我们的项目添加所有必要的依赖性.

Optionally, we can also add spring-cloud-netflix to our dependencyManagement section and rely on its specification of the versions of the artifacts:

作为选择,我们也可以将spring-cloud-netflix添加到我们的dependencyManagement部分,并依靠其对工件版本的规范。

<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>

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

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

4. Usage

4.使用情况

Once we add the required dependency, we’ll be able to access the properties managed by the framework:

一旦我们添加了所需的依赖关系,我们就能访问框架所管理的属性

DynamicStringProperty dynamicProperty 
  = DynamicPropertyFactory.getInstance()
  .getStringProperty("baeldung.archaius.property", "default value");

String propertyCurrentValue = dynamicProperty.get();

Let’s work on a short example to see how this is available just out-of-the-box.

让我们通过一个简短的例子来看看这一点是如何开箱即用的。

4.1. Quick Example

4.1.快速实例

By default, it manages dynamically all the properties defined in a file named config.properties in the application’s classpath.

默认情况下,它动态管理应用程序classpath中一个名为config.properties的文件中定义的所有属性

So let’s add it to our resources folder with some arbitrary properties:

因此,让我们把它添加到我们的资源文件夹中,加上一些任意的属性。

#config.properties
baeldung.archaius.properties.one=one FROM:config.properties

Now we’ll need a way to check the properties’ values at any specific moment. In this case, we’ll create a RestController that retrieves the values as a JSON response:

现在我们需要一种方法来检查任何特定时刻的属性值。在这种情况下,我们将创建一个RestController,以JSON响应的方式检索值。

@RestController
public class ConfigPropertiesController {
	
    private DynamicStringProperty propertyOneWithDynamic
      = DynamicPropertyFactory.getInstance()
      .getStringProperty("baeldung.archaius.properties.one", "not found!");
	
    @GetMapping("/property-from-dynamic-management")
    public String getPropertyValue() {
	return propertyOneWithDynamic.getName() + ": " + propertyOneWithDynamic.get();
    }
}

Let’s try it out. We can send a request to this endpoint, and the service will retrieve the values stored in config.properties as expected.

让我们试试吧。我们可以向这个端点发送一个请求,服务将检索存储在config.properties中的值,正如预期。

No big deal so far, right? Ok, let’s go on and change the values of the property in the classpath file, without restarting the service. As a result, after a minute or so, a call to the endpoint should retrieve the new values. Pretty cool, isn’t it?

到目前为止没有什么大问题,对吗?好吧,让我们继续,改变classpath文件中的属性值,而不重启服务。结果,一分钟左右后,对端点的调用应该能检索到新的值。很酷,不是吗?

Next, we’ll try to understand what’s going on under the hood.

接下来,我们将尝试了解引擎盖下发生了什么。

5. How Does It Work?

5.它是如何工作的?

First of all, let’s attempt to comprehend the big picture.

首先,让我们尝试理解一下大局。

Archaius is an extension of the Apache’s Commons Configuration library, adding some nice features like a polling framework for dynamic sources, with high throughput and thread-safe implementation.

Archaius是Apache的Commons配置库的扩展,增加了一些不错的功能,如动态源的轮询框架,具有高吞吐量和线程安全的实现。

The spring-cloud-netflix-archaius library comes then into play, merging all the different property sources, and auto-configuring the Archaius tools with these sources.

spring-cloud-netflix-archaius库随后开始发挥作用,合并所有不同的属性源,并使用这些源自动配置Archaius工具。

5.1. The Netflix Archaius Library

5.1.Netflix Archaius图书馆

It operates defining a Composite Configuration, a collection of various configurations obtained from different sources.

它的操作定义了一个复合配置,即从不同来源获得的各种配置的集合。

Moreover, some of those Configuration Sources might support being polled at runtime for changes. Archaius provides interfaces and some pre-defined implementations to configure these types of sources.

此外,其中一些配置源可能支持在运行时轮询更改。Archaius提供接口和一些预定义的实现来配置这些类型的源。

The collection of sources is hierarchized so that if a property is present in multiple configurations, the final value will be the one in the topmost slot.

来源的集合是分层的,因此如果一个属性出现在多个配置中,最终的值将是最上面的槽中的那个。

Finally, a ConfigurationManager handles the system-wide Configuration and deployment context. It can install the final Composite Configuration, or retrieve the installed one for modification.

最后,一个ConfigurationManager处理整个系统的配置和部署环境。它可以安装最终的复合配置,或检索已安装的配置进行修改。

5.2. Spring Cloud Support

5.2.Spring云支持

The main task of the Spring Cloud Archaius library is to merge all the different configuration sources as a ConcurrentCompositeConfiguration and install it using the ConfigurationManager.

Spring Cloud Archaius库的主要任务是将所有不同的配置源合并为一个ConcurrentCompositeConfiguration并使用ConfigurationManager进行安装。

The order of precedence in which the library defines the sources is:

该库定义来源的优先顺序是。

  1. Any Apache Common Configuration AbstractConfiguration bean defined in the context
  2. All the sources defined in the Autowired Spring ConfigurableEnvironment
  3. The default Archaius sources, which we saw in the example above
  4. Apache’s SystemConfiguration and EnvironmentConfiguration sources

Another useful feature this Spring Cloud library provides is the definition of an Actuator Endpoint to monitor and interact with the properties. Its usage is out of the scope of this tutorial.

这个Spring Cloud库提供的另一个有用的功能是定义了一个执行器端点来监控并与属性互动。它的使用不在本教程的范围之内。

6. Adapting and Extending the Archaius Configuration

6.改造和扩展Archaius配置

Now that we have a better understanding of how Archaius works, we are in good shape to analyze how to adapt the configuration to our application, or how to extend the functionality using our configuration sources.

现在我们对Archaius的工作原理有了更好的了解,我们可以很好地分析如何使配置适应我们的应用,或者如何使用我们的配置源扩展功能。

6.1. Archaius Supported Configuration Properties

6.1.Archaius支持的配置属性

If we want Archaius to take into account other configuration files similar to the config.properties one, we can define the archaius.configurationSource.additionalUrls system property.

如果我们想让Archaius考虑到与config.properties类似的其他配置文件,我们可以定义archaius.configurationSource.an additionalUrlssystem属性。

The value is parsed to a list of URLs separated by a comma, so, for example, we can add this system property when we launch the application:

该值被解析为一个由逗号分隔的URL列表,因此,例如,我们可以在启动应用程序时添加这个系统属性。

-Darchaius.configurationSource.additionalUrls=
  "classpath:other-dir/extra.properties,
  file:///home/user/other-extra.properties"

Archaius will read the config.properties file first, and then the other ones, in the specified order. Because of this, the properties defined in the latter files will have priority over the prior ones.

Archaius会先读取config.properties文件,然后按照指定顺序读取其他文件。正因为如此,后面的文件中定义的属性将优先于前面的文件。

There are a couple of other system properties we can use to configure various aspects of the Archaius default configuration:

还有一些其他的系统属性,我们可以用来配置Archaius默认配置的各方面。

  • archaius.configurationSource.defaultFileName: the default configuration file name in the classpath
  • archaius.fixedDelayPollingScheduler.initialDelayMills: initial delay before reading the configuration source
  • archaius.fixedDelayPollingScheduler.delayMills: delay between two reads of the source; the default value is 1 minute

6.2. Adding Additional Configuration Sources with Spring

6.2.用Spring添加额外的配置源

How could we add a different Configuration Source to be managed by the described framework? And how could we manage dynamic properties with higher precedence than the ones defined in the Spring Environment?

我们怎样才能添加一个不同的配置源来由所述的框架管理?我们怎样才能管理比Spring环境中定义的优先级更高的动态属性?

Reviewing what we mentioned in section 4.2, we can realize that the highest configurations in the Composite Configuration defined by Spring are the AbstractConfiguration beans defined in the context.

回顾我们在第4.2节提到的内容,我们可以意识到Spring定义的复合配置中的最高配置是上下文中定义的AbstractConfigurationBean。

Thus, all we need to do is add an implementation of this Apache’s abstract class to our Spring Context using some of the functionality provided by Archaius, and the Spring’s autoconfiguration will spontaneously add it to the managed configuration properties.

因此,我们需要做的就是使用Archaius提供的一些功能将这个Apache的抽象类的实现添加到我们的Spring Context中,Spring的自动配置会自发地将其添加到托管配置属性中

To keep things simple, we’ll see an example where we configure a properties file similar to the default config.properties but with the difference of having a higher precedence than the rest of Spring environment and application properties:

为了保持简单,我们将看到一个例子,我们配置一个类似于默认config.properties的属性文件,但不同的是,其优先级高于Spring环境和应用程序的其他属性。

@Bean
public AbstractConfiguration addApplicationPropertiesSource() {
    URL configPropertyURL = (new ClassPathResource("other-config.properties")).getURL();
    PolledConfigurationSource source = new URLConfigurationSource(configPropertyURL);
    return new DynamicConfiguration(source, new FixedDelayPollingScheduler());
}

Lucky for us, it contemplates several configuration sources that we can set up with almost no effort. Their configuration is out of the scope of this introductory tutorial.

我们很幸运,它考虑了几个配置源,我们几乎不费吹灰之力就可以设置好。它们的配置不在本介绍性教程的范围之内。

7. Conclusion

7.结语

To sum up, we’ve learned about Archaius and some of the cool features it offers to take advantage of configuration management.

总而言之,我们已经了解了Archaius和它提供的一些利用配置管理的很酷的功能。

Also, we saw how the Spring Cloud autoconfiguration library comes into play allowing us to use this library’s API conveniently.

此外,我们还看到了Spring Cloud自动配置库是如何发挥作用的,使我们能够方便地使用这个库的API。

Once more, we can find all the examples shown in this tutorial and others in our Github repo.

再一次,我们可以在我们的Github repo中找到本教程中显示的所有例子和其他例子。