快速入门:将功能标志添加到 Spring Boot 应用Quickstart: Add feature flags to a Spring Boot app

在本快速入门中,你要将 Azure 应用程序配置合并到 Spring Boot Web 应用中,以创建功能管理的端到端实现。In this quickstart, you incorporate Azure App Configuration into a Spring Boot web app to create an end-to-end implementation of feature management. 可以使用应用程序配置服务集中存储所有功能标志并控制其状态。You can use the App Configuration service to centrally store all your feature flags and control their states.

Spring Boot 功能管理库使用全面的功能标志支持扩展了该框架。The Spring Boot Feature Management libraries extend the framework with comprehensive feature flag support. 这些库 依赖于任何 Azure 库。These libraries do not have a dependency on any Azure libraries. 它们可以通过其 Spring Boot 配置提供程序无缝集成到应用程序配置。They seamlessly integrate with App Configuration through its Spring Boot configuration provider.

先决条件Prerequisites

创建应用程序配置实例Create an App Configuration instance

  1. 若要创建新应用程序配置存储区,请登录 Azure 门户To create a new App Configuration store, sign in to the Azure portal. 在主页的左上角,选择“创建资源” 。In the upper-left corner of the home page, select Create a resource. 在“搜索市场”框中,输入“应用程序配置”并选择 Enter 。In the Search the Marketplace box, enter App Configuration and select Enter.

    搜索应用配置

  2. 在搜索结果中选择“应用程序配置”,然后选择“创建” 。Select App Configuration from the search results, and then select Create.

    选择“创建”

  3. 在“创建应用配置”窗格中,输入以下设置:On the Create App Configuration pane, enter the following settings:

    设置Setting 建议的值Suggested value 说明Description
    订阅Subscription 订阅Your subscription 选择要用来测试应用配置的 Azure 订阅。Select the Azure subscription that you want to use to test App Configuration. 如果帐户只有一个订阅,则会自动选择该订阅并且不显示“订阅”列表 。If your account has only one subscription, it's automatically selected and the Subscription list isn't displayed.
    资源组Resource group AppConfigTestResources AppConfigTestResources 为应用程序配置存储区资源选择或创建资源组。Select or create a resource group for your App Configuration store resource. 此组可用于组织多个资源,删除该资源组可以同时删除这些资源。This group is useful for organizing multiple resources that you might want to delete at the same time by deleting the resource group. 有关详细信息,请参阅使用资源组管理 Azure 资源For more information, see Use resource groups to manage your Azure resources.
    资源名称Resource name 全局唯一名称Globally unique name 输入要用于应用程序配置存储区资源的唯一资源名称。Enter a unique resource name to use for the App Configuration store resource. 该名称必须是包含 5 到 50 个字符的字符串,只能包含数字、字母和 - 字符。The name must be a string between 5 and 50 characters and contain only numbers, letters, and the - character. 该名称的开头或末尾不能是 - 字符。The name can't start or end with the - character.
    位置Location 中国东部 2China East 2 使用“位置”指定在其中托管应用配置存储区的地理位置 。Use Location to specify the geographic location in which your app configuration store is hosted. 为获得最佳性能,请在应用程序的其他组件所在的同一区域创建资源。For the best performance, create the resource in the same region as other components of your application.
    定价层Pricing tier 免费Free 选择所需的定价层。Select the desired pricing tier. 有关详细信息,请参阅应用配置定价页For more information, see the App Configuration pricing page.
  4. 选择“查看 + 创建”以验证自己的设置 。Select Review + create to validate your settings.

  5. 选择“创建”。Select Create. 部署可能需要几分钟。The deployment might take a few minutes.

  6. 部署完成后,导航到“应用程序配置”资源。After the deployment finishes, navigate to the App Configuration resource. 选择“设置” > “访问密钥”。Select Settings > Access keys. 记下只读主密钥连接字符串。Make a note of the primary read-only key connection string. 稍后将使用此连接字符串来配置应用程序,以与创建的应用程序配置存储区进行通信。You'll use this connection string later to configure your application to communicate with the App Configuration store that you created.

  1. 选择“功能管理器” > “+添加”以添加名为 Beta 的功能标志。 Select Feature Manager > +Add to add a feature flag called Beta.

    启用名为 Beta 的功能标志Enable feature flag named Beta

    暂时不定义 labelLeave label undefined for now.

创建 Spring Boot 应用Create a Spring Boot app

使用 Spring Initializr 创建一个新 Spring Boot 项目。Use the Spring Initializr to create a new Spring Boot project.

  1. 浏览到 https://start.spring.io/Browse to https://start.spring.io/.

  2. 指定以下选项:Specify the following options:

    • 使用 Java 生成一个 Maven 项目。Generate a Maven project with Java.
    • 指定一个其值大于或等于 2.0 的 Spring Boot 版本。Specify a Spring Boot version that's equal to or greater than 2.0.
    • 指定应用程序的“组”和“项目”名称。 Specify the Group and Artifact names for your application. 本文使用 com.exampledemoThis article uses com.example and demo.
    • 添加 Spring Web 依赖项。Add the Spring Web dependency.
  3. 指定上述选项后,选择“生成项目” 。After you specify the previous options, select Generate Project. 出现提示时,将项目下载到本地计算机。When prompted, download the project to your local computer.

添加功能管理Add feature management

  1. 在本地系统中提取文件后,即可对 Spring Boot 应用程序进行编辑。After you extract the files on your local system, your Spring Boot application is ready for editing. 在应用的根目录中找到 pom.xmlLocate pom.xml in the root directory of your app.

  2. 在文本编辑器中打开 pom.xml 文件,将以下内容添加到 <dependencies> 列表中:Open the pom.xml file in a text editor and add the following to the list of <dependencies>:

    Spring Cloud 1.1.xSpring Cloud 1.1.x

    <dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>spring-cloud-azure-appconfiguration-config-web</artifactId>
        <version>1.1.5</version>
    </dependency>
    <dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>spring-cloud-azure-feature-management-web</artifactId>
        <version>1.1.5</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    

    Spring Cloud 1.2.xSpring Cloud 1.2.x

    <dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>spring-cloud-azure-appconfiguration-config-web</artifactId>
        <version>1.2.7</version>
    </dependency>
    <dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>spring-cloud-azure-feature-management-web</artifactId>
        <version>1.2.7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    

备注

有一个非 Web 功能管理库不依赖于 spring-web。There is a non-web Feature Management Library that doesn't have a dependency on spring-web. 请参阅 GitHub 的文档来了解差异。Refer to GitHub's documentation for differences.

连接到应用程序配置存储区Connect to an App Configuration store

  1. 导航到应用的 resources 目录并打开 bootstrap.propertiesNavigate to the resources directory of your app and open bootstrap.properties. 如果该文件不存在,请创建它。If the file does not exist, create it. 将以下行添加到该文件。Add the following line to the file.

    spring.cloud.azure.appconfiguration.stores[0].connection-string= ${APP_CONFIGURATION_CONNECTION_STRING}
    
  2. 在配置存储的应用程序配置门户的侧栏中选择 Access keysIn the App Configuration portal for your config store, select Access keys from the sidebar. 选择“只读密钥”选项卡。复制主连接字符串的值。Select the Read-only keys tab. Copy the value of the primary connection string.

  3. 使用变量名称 APP_CONFIGURATION_CONNECTION_STRING 添加环境变量形式的主连接字符串。Add the primary connection string as an environment variable using the variable name APP_CONFIGURATION_CONNECTION_STRING.

  4. 打开主应用程序 Java 文件,并添加 @EnableConfigurationProperties以启用此功能。Open the main application Java file, and add @EnableConfigurationProperties to enable this feature.

    package com.example.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    @EnableConfigurationProperties(MessageProperties.class)
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    }
    
  5. 在应用的包目录中创建名为 MessageProperties.java 的新 Java 文件 。Create a new Java file named MessageProperties.java in the package directory of your app.

    package com.example.demo;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @ConfigurationProperties(prefix = "config")
    public class MessageProperties {
        private String message;
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    }
    
  6. 在应用的包目录中创建新的名为 HelloController.java 的 Java 文件 。Create a new Java file named HelloController.java in the package directory of your app.

    package com.example.demo;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    
    import com.microsoft.azure.spring.cloud.feature.manager.FeatureManager;
    import org.springframework.web.bind.annotation.GetMapping;
    
    
    @Controller
    @ConfigurationProperties("controller")
    public class HelloController {
    
        private FeatureManager featureManager;
    
        public HelloController(FeatureManager featureManager) {
            this.featureManager = featureManager;
        }
    
        @GetMapping("/welcome")
        public String mainWithParam(Model model) {
            model.addAttribute("Beta", featureManager.isEnabledAsync("featureManagement.Beta").block());
            return "welcome";
        }
    }
    
  7. 在应用的 templates 目录中,创建名为 welcome.html 的新 HTML 文件。Create a new HTML file named welcome.html in the templates directory of your app.

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Feature Management with Spring Cloud Azure</title>
    
        <link rel="stylesheet" href="/css/main.css">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    
        <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    
    </head>
    <body>
        <header>
        <!-- Fixed navbar -->
        <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
            <a class="navbar-brand" href="#">TestFeatureFlags</a>
            <button class="navbar-toggler" aria-expanded="false" aria-controls="navbarCollapse" aria-label="Toggle navigation" type="button" data-target="#navbarCollapse" data-toggle="collapse">
            <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarCollapse">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item" th:if="${Beta}">
                <a class="nav-link" href="#">Beta</a>
                </li>
                <li class="nav-item">
                <a class="nav-link" href="#">Privacy</a>
                </li>
            </ul>
            </div>
        </nav>
        </header>
        <div class="container body-content">
            <h1 class="mt-5">Welcome</h1>
            <p>Learn more about <a href="https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/appconfiguration/azure-spring-cloud-feature-management/README.md">Feature Management with Spring Cloud Azure</a></p>
    
        </div>
        <footer class="footer">
            <div class="container">
            <span class="text-muted">&copy; 2019 - Projects</span>
        </div>
    
        </footer>
    </body>
    </html>
    
    
  8. static 下创建名为 CSS 的新文件夹,并在其中创建名为 main.css 的新 CSS 文件。Create a new folder named CSS under static and inside of it a new CSS file named main.css.

    html {
     position: relative;
     min-height: 100%;
    }
    body {
     margin-bottom: 60px;
    }
    .footer {
     position: absolute;
     bottom: 0;
     width: 100%;
     height: 60px;
     line-height: 60px;
     background-color: #f5f5f5;
    }
    
    body > .container {
     padding: 60px 15px 0;
    }
    
    .footer > .container {
     padding-right: 15px;
     padding-left: 15px;
    }
    
    code {
     font-size: 80%;
    }
    

在本地生成并运行应用Build and run the app locally

  1. 使用 Maven 生成 Spring Boot 应用程序,然后运行该程序。Build your Spring Boot application with Maven and run it.

    mvn clean package
    mvn spring-boot:run
    
  2. 打开浏览器窗口,访问 URL:http://localhost:8080/welcomeOpen a browser window, and go to the URL: http://localhost:8080/welcome.

    屏幕截图显示一个浏览器窗口,其中显示了“欢迎”消息。

  3. 在应用程序配置门户中选择“功能管理器”,并将“Beta”密钥的状态更改为“打开”: In the App Configuration portal select Feature Manager, and change the state of the Beta key to On:

    密钥Key 状态State
    BetaBeta 启用On
  4. 刷新浏览器页面,查看新的配置设置。Refresh the browser page to see the new configuration settings.

    屏幕截图显示一个浏览器窗口,其中显示了“欢迎”消息和标注的 Beta 链接。

清理资源Clean up resources

如果不想继续使用本文中创建的资源,请删除此处创建的资源组以避免产生费用。If you do not want to continue using the resources created in this article, delete the resource group you created here to avoid charges.

重要

删除资源组的操作不可逆。Deleting a resource group is irreversible. 将永久删除资源组以及其中的所有资源。The resource group and all the resources in it are permanently deleted. 请确保不要意外删除错误的资源组或资源。Make sure that you don't accidentally delete the wrong resource group or resources. 如果在包含要保留的其他资源的资源组中创建了本文的资源,请从相应的窗格中单独删除每个资源,而不是删除该资源组。If you created the resources for this article inside a resource group that contains other resources you want to keep, delete each resource individually from its respective pane instead of deleting the resource group.

  1. 登录到 Azure 门户,然后选择“资源组”。Sign in to the Azure portal, and select Resource groups.
  2. 在“按名称筛选”框中,输入资源组的名称。In the Filter by name box, enter the name of your resource group.
  3. 在结果列表中,选择资源组名称以查看概述。In the result list, select the resource group name to see an overview.
  4. 选择“删除资源组”。Select Delete resource group.
  5. 系统会要求确认是否删除资源组。You're asked to confirm the deletion of the resource group. 重新键入资源组的名称进行确认,然后选择“删除” 。Enter the name of your resource group to confirm, and select Delete.

片刻之后,将会删除该资源组及其所有资源。After a few moments, the resource group and all its resources are deleted.

后续步骤Next steps

在本快速入门中,你已创建一个新的应用程序配置存储,并已使用它来通过功能管理库管理 Spring Boot Web 应用中的功能。In this quickstart, you created a new App Configuration store and used it to manage features in a Spring Boot web app via the Feature Management libraries.