教程:在 Spring Boot 应用中使用功能标志Tutorial: Use feature flags in a Spring Boot app

Spring Boot Core 功能管理库支持在 Spring Boot 应用程序中实施功能标志。The Spring Boot Core Feature Management libraries provide support for implementing feature flags in a Spring Boot application. 使用这些库能够以声明方式将功能标志添加到代码。These libraries allow you to declaratively add feature flags to your code.

功能管理库还会在幕后管理功能标志生命周期。The Feature Management libraries also manage feature flag lifecycles behind the scenes. 例如,这些库可刷新和缓存标志状态,或者保证标志状态在请求调用期间保持不变。For example, the libraries refresh and cache flag states, or guarantee a flag state to be immutable during a request call. 此外,Spring Boot 库还提供集成,包括 MVC 控制器操作、路由和中间件。In addition, the Spring Boot library offers integrations, including MVC controller actions, routes, and middleware.

将功能标志添加到 Spring Boot 应用快速入门介绍了在 Spring Boot 应用程序中添加功能标志的多种方法。The Add feature flags to a Spring Boot app Quickstart shows several ways to add feature flags in a Spring Boot application. 本教程将更详细地介绍这些方法。This tutorial explains these methods in more detail.

在本教程中,您将学习如何执行以下操作:In this tutorial, you will learn how to:

  • 在应用程序的关键组件中添加功能标志,以控制功能可用性。Add feature flags in key parts of your application to control feature availability.
  • 使用应用程序配置来管理功能标志时,与应用程序配置相集成。Integrate with App Configuration when you're using it to manage feature flags.

设置功能管理Set up feature management

Spring Boot 功能管理器 FeatureManager 从框架的本机配置系统获取功能标志。The Spring Boot feature manager FeatureManager gets feature flags from the framework's native configuration system. 因此,可以使用 Spring Boot 支持的任何配置源(包括本地 bootstrap.yml 文件或环境变量)来定义应用程序的功能标志。As a result, you can define your application's feature flags by using any configuration source that Spring Boot supports, including the local bootstrap.yml file or environment variables. FeatureManager 依赖于依赖项注入。FeatureManager relies on dependency injection. 可以使用标准约定来注册功能管理服务。You can register the feature management services by using standard conventions:

private FeatureManager featureManager;

public HelloController(FeatureManager featureManager) {
    this.featureManager = featureManager;
}

我们建议将功能标志保留在应用程序的外部,并单独对其进行管理。We recommend that you keep feature flags outside the application and manage them separately. 这样便可以随时修改标志状态,并使这些更改在应用程序中立即生效。Doing so allows you to modify flag states at any time and have those changes take effect in the application right away. 应用程序配置提供一个中心位置用于通过专用门户 UI 来组织和控制所有功能标志。App Configuration provides a centralized place for organizing and controlling all your feature flags through a dedicated portal UI. 应用程序配置还直接通过其 Spring Boot 客户端库将标志传送到应用程序。App Configuration also delivers the flags to your application directly through its Spring Boot client libraries.

将 Spring Boot 应用程序连接到应用程序配置的最简单方法是使用配置提供程序:The easiest way to connect your Spring Boot application to App Configuration is through the configuration provider:

Spring Cloud 1.1.xSpring Cloud 1.1.x

<dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>spring-cloud-azure-feature-management-web</artifactId>
    <version>1.1.2</version>
</dependency>

Spring Cloud 1.2.xSpring Cloud 1.2.x

<dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>spring-cloud-azure-feature-management-web</artifactId>
    <version>1.2.2</version>
</dependency>

功能标志声明Feature flag declaration

每个功能标志有两个组成部分:一个名称,以及用于评估功能状态是否为“打开”(即,其值为 True)的一个或多个筛选器的列表。 Each feature flag has two parts: a name and a list of one or more filters that are used to evaluate if a feature's state is on (that is, when its value is True). 筛选器定义有关何时应启用某个功能的用例。A filter defines a use case for when a feature should be turned on.

如果某个功能标志包含多个筛选器,则会按顺序遍历筛选器列表,直到其中一个筛选器确定应启用该功能。When a feature flag has multiple filters, the filter list is traversed in order until one of the filters determines the feature should be enabled. 此时,该功能标志为“打开”,并会跳过所有剩余的筛选器结果。 At that point, the feature flag is on, and any remaining filter results are skipped. 如果没有任何筛选器指示应启用该功能,则表示该功能标志为“关闭”。 If no filter indicates the feature should be enabled, the feature flag is off.

功能管理器支持将 application.yml 用作功能标志的配置源。The feature manager supports application.yml as a configuration source for feature flags. 以下示例演示如何在 YAML 文件中设置功能标志:The following example shows how to set up feature flags in a YAML file:

feature-management:
  feature-set:
    feature-a: true
    feature-b: false
    feature-c:
      enabled-for:
        -
          name: Percentage
          parameters:
            value: 50

按照约定,此 YML 文档的 feature-management 节用于功能标志设置。By convention, the feature-management section of this YML document is used for feature flag settings. 以上示例演示了三个功能标志,其筛选器已在 EnabledFor 属性中定义:The prior example shows three feature flags with their filters defined in the EnabledFor property:

  • feature-a 状态为“打开”。 feature-a is on.
  • feature-b 状态为“关闭”。 feature-b is off.
  • feature-c 指定包含 parameters 属性的名为 Percentage 的筛选器。feature-c specifies a filter named Percentage with a parameters property. Percentage 是可配置的筛选器。Percentage is a configurable filter. 在此示例中,Percentage 指定打开 feature-c 标志的概率为 50%。 In this example, Percentage specifies a 50-percent probability for the feature-c flag to be on.

功能标志检查Feature flag checks

功能管理的基本模式是首先检查功能标志是否设置为“打开”。 The basic pattern of feature management is to first check if a feature flag is set to on. 如果是,则功能管理器将运行该功能包含的操作。If so, the feature manager then runs the actions that the feature contains. 例如:For example:

private FeatureManager featureManager;
...
if (featureManager.isEnabledAsync("feature-a").block()) {
    // Run the following code
}

依赖项注入Dependency injection

在 Spring Boot 中,可以通过依赖项注入访问功能管理器 FeatureManagerIn Spring Boot, you can access the feature manager FeatureManager through dependency injection:

@Controller
@ConfigurationProperties("controller")
public class HomeController {
    private FeatureManager featureManager;

    public HomeController(FeatureManager featureManager) {
        this.featureManager = featureManager;
    }
}

控制器操作Controller actions

在 MVC 控制器中,使用 @FeatureGate 属性控制是否启用特定的操作。In MVC controllers, you use the @FeatureGate attribute to control whether a specific action is enabled. 以下 Index 操作要求 feature-a 状态为“打开”才能运行该操作: The following Index action requires feature-a to be on before it can run:

@GetMapping("/")
@FeatureGate(feature = "feature-a")
public String index(Model model) {
    ...
}

当由于控制功能标志状态为“关闭”而阻止了 MVC 控制器或操作时,将调用已注册的 IDisabledFeaturesHandler接口。 When an MVC controller or action is blocked because the controlling feature flag is off, a registered IDisabledFeaturesHandler interface is called. 默认的 IDisabledFeaturesHandler 接口向客户端返回 404 状态代码,但不返回响应正文。The default IDisabledFeaturesHandler interface returns a 404 status code to the client with no response body.

MVC 筛选器MVC filters

可以设置 MVC 筛选器,以根据功能标志的状态激活这些筛选器。You can set up MVC filters so that they're activated based on the state of a feature flag. 以下代码添加名为 FeatureFlagFilter 的 MVC 筛选器。The following code adds an MVC filter named FeatureFlagFilter. 仅当已启用 feature-a 时,才会在 MVC 管道内部触发此筛选器。This filter is triggered within the MVC pipeline only if feature-a is enabled.

@Component
public class FeatureFlagFilter implements Filter {

    @Autowired
    private FeatureManager featureManager;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if(!featureManager.isEnabledAsync("feature-a").block()) {
            chain.doFilter(request, response);
            return;
        }
        ...
        chain.doFilter(request, response);
    }
}

路由Routes

可以使用功能标志来重定向路由。You can use feature flags to redirect routes. 以下代码从启用的 feature-a 重定向用户:The following code will redirect a user from feature-a is enabled:

@GetMapping("/redirect")
@FeatureGate(feature = "feature-a", fallback = "/getOldFeature")
public String getNewFeature() {
    // Some New Code
}

@GetMapping("/getOldFeature")
public String getOldFeature() {
    // Some New Code
}

后续步骤Next steps

本教程已介绍如何使用 spring-cloud-azure-feature-management-web 库在 Spring Boot 应用程序中实施功能标志。In this tutorial, you learned how to implement feature flags in your Spring Boot application by using the spring-cloud-azure-feature-management-web libraries. 有关 Spring Boot 和应用程序配置中的功能管理支持的详细信息,请参阅以下资源:For more information about feature management support in Spring Boot and App Configuration, see the following resources: