教程:在 Azure Functions 应用中使用动态配置Tutorial: Use dynamic configuration in an Azure Functions app

应用程序配置 .NET Standard 配置提供程序支持缓存和动态刷新由应用程序活动驱动的配置。The App Configuration .NET Standard configuration provider supports caching and refreshing configuration dynamically driven by application activity. 本教程演示如何在代码中实现动态配置更新。This tutorial shows how you can implement dynamic configuration updates in your code. 它建立在本快速入门中介绍的 Azure Functions 应用之上。It builds on the Azure Functions app introduced in the quickstarts. 在继续本教程之前,请先完成使用 Azure 应用程序配置创建 Azure Functions 应用这一教程。Before you continue, finish Create an Azure functions app with Azure App Configuration first.

在本教程中,你将了解如何执行以下操作:In this tutorial, you learn how to:

  • 设置 Azure Functions 应用,使其能够更新配置以响应应用程序配置存储区中的更改。Set up your Azure Functions app to update its configuration in response to changes in an App Configuration store.
  • 将最新配置注入到 Azure Functions 调用中。Inject the latest configuration to your Azure Functions calls.

先决条件Prerequisites

从应用配置重载数据Reload data from App Configuration

  1. 打开 Function1.cs 。Open Function1.cs. 除了 static 属性 Configuration 之外,还可添加新的 static 属性 ConfigurationRefresher 以保留 IConfigurationRefresher 的单一实例,该实例在稍后调用 Functions 时将用于通知配置更新。In addition to the static property Configuration, add a new static property ConfigurationRefresher to keep a singleton instance of IConfigurationRefresher that will be used to signal configuration updates during Functions calls later.

    private static IConfiguration Configuration { set; get; }
    private static IConfigurationRefresher ConfigurationRefresher { set; get; }
    
  2. 更新此构造函数并使用 ConfigureRefresh 方法指定从应用程序配置存储区中刷新此设置。Update the constructor and use the ConfigureRefresh method to specify the setting to be refreshed from the App Configuration store. 使用 GetRefresher 方法检索 IConfigurationRefresher 的实例。An instance of IConfigurationRefresher is retrieved using GetRefresher method. 我们还可以将配置缓存过期时间范围从默认的 30 秒更改为 1 分钟。Optionally, we also change the configuration cache expiration time window to 1 minute from the default 30 seconds.

    static Function1()
    {
        var builder = new ConfigurationBuilder();
        builder.AddAzureAppConfiguration(options =>
        {
            options.Connect(Environment.GetEnvironmentVariable("ConnectionString"))
                   .ConfigureRefresh(refreshOptions =>
                        refreshOptions.Register("TestApp:Settings:Message")
                                      .SetCacheExpiration(TimeSpan.FromSeconds(60))
            );
            ConfigurationRefresher = options.GetRefresher();
        });
        Configuration = builder.Build();
    }
    
  3. 更新 Run 方法,并在 Functions 调用开始时通知使用 TryRefreshAsync 方法刷新配置。Update the Run method and signal to refresh the configuration using the TryRefreshAsync method at the beginning of the Functions call. 如果未到达缓存过期时间范围,则将不会进行操作。This will be no-op if the cache expiration time window isn't reached. 如果希望在不受阻止的情况下刷新配置,请删除 await 运算符。Remove the await operator if you prefer the configuration to be refreshed without blocking.

    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");
    
        await ConfigurationRefresher.TryRefreshAsync(); 
    
        string keyName = "TestApp:Settings:Message";
        string message = Configuration[keyName];
    
        return message != null
            ? (ActionResult)new OkObjectResult(message)
            : new BadRequestObjectResult($"Please create a key-value with the key '{keyName}' in App Configuration.");
    }
    

在本地测试函数Test the function locally

  1. 设置名为“ConnectionString”的环境变量,并将其设置为应用程序配置存储区的访问键 。Set an environment variable named ConnectionString, and set it to the access key to your app configuration store. 如果使用 Windows 命令提示符,则请运行以下命令并重启命令提示符,这样更改才会生效:If you use the Windows command prompt, run the following command and restart the command prompt to allow the change to take effect:

    setx ConnectionString "connection-string-of-your-app-configuration-store"
    

    如果使用 Windows PowerShell,请运行以下命令:If you use Windows PowerShell, run the following command:

    $Env:ConnectionString = "connection-string-of-your-app-configuration-store"
    

    如果使用 macOS 或 Linux,则请运行以下命令:If you use macOS or Linux, run the following command:

    export ConnectionString='connection-string-of-your-app-configuration-store'
    
  2. 若要测试函数,请按 F5。To test your function, press F5. 如果系统提示,请按 Visual Studio 的请求下载和安装 Azure Functions Core (CLI) 工具 。If prompted, accept the request from Visual Studio to download and install Azure Functions Core (CLI) tools. 你还需要启用防火墙例外,这样工具才能处理 HTTP 请求。You might also need to enable a firewall exception so that the tools can handle HTTP requests.

  3. 从 Azure Functions 运行时输出复制函数的 URL。Copy the URL of your function from the Azure Functions runtime output.

    在 VS 中的函数调试快速入门

  4. 将 HTTP 请求的 URL 粘贴到浏览器的地址栏中。Paste the URL for the HTTP request into your browser's address bar. 下图显示了浏览器中函数返回的本地 GET 请求的响应。The following image shows the response in the browser to the local GET request returned by the function.

    本地函数启动快速入门

  5. 登录 Azure 门户Sign in to the Azure portal. 选择“所有资源”,然后选择在快速入门中创建的应用程序配置存储区实例 。Select All resources, and select the App Configuration store instance that you created in the quickstart.

  6. 选择“配置资源管理器”并更新以下密钥值 :Select Configuration Explorer, and update the values of the following key:

    密钥Key Value
    TestApp:Settings:MessageTestApp:Settings:Message Azure 应用配置的数据 - 已更新Data from Azure App Configuration - Updated
  7. 多次刷新浏览器。Refresh the browser a few times. 如果缓存的设置在一分钟后过期,则页面会显示 Functions 调用的响应已有更新的值。When the cached setting expires after a minute, the page shows the response of the Functions call with updated value.

    本地函数刷新快速入门

本教程中使用的示例代码可从应用程序配置 GitHub 存储库下载The example code used in this tutorial can be downloaded from App Configuration GitHub repo

清理资源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

在本教程中,你学习了如何使 Azure Functions 应用能够动态刷新来自应用程序配置的配置设置。In this tutorial, you enabled your Azure Functions app to dynamically refresh configuration settings from App Configuration. 若要了解如何使用 Azure 托管标识来简化对应用程序配置的访问,请继续学习下一篇教程。To learn how to use an Azure managed identity to streamline the access to App Configuration, continue to the next tutorial.