自动备份应用程序配置存储区Back up App Configuration stores automatically

本文介绍如何设置从主 Azure 应用程序配置存储区到辅助存储区的自动键值备份。In this article, you'll learn how to set up an automatic backup of key-values from a primary Azure App Configuration store to a secondary store. 自动备份使用 Azure 事件网格与应用程序配置的集成。The automatic backup uses the integration of Azure Event Grid with App Configuration.

设置自动备份后,对于配置存储区中键值的任何更改,应用程序配置会向 Azure 事件网格发布事件。After you set up the automatic backup, App Configuration will publish events to Azure Event Grid for any changes made to key-values in a configuration store. 事件网格支持各种 Azure 服务,用户可以从这些服务中订阅在创建、更新或删除键值时发出的事件。Event Grid supports a variety of Azure services from which users can subscribe to the events emitted whenever key-values are created, updated, or deleted.

概述Overview

在本文中,你将使用 Azure 队列存储从事件网格接收事件,并使用 Azure Functions 的计时器触发器批量处理队列中的事件。In this article, you'll use Azure Queue storage to receive events from Event Grid and use a timer-trigger of Azure Functions to process events in the queue in batches.

当触发函数时,根据事件,函数将从主应用程序配置存储区获取已更改的键的最新值,并相应更新辅助存储。When a function is triggered, based on the events, it will fetch the latest values of the keys that have changed from the primary App Configuration store and update the secondary store accordingly. 此设置有助于在一个备份操作中结合在短时间内发生的多个更改,从而避免向应用程序配置存储区发出过多的请求。This setup helps combine multiple changes that occur in a short period in one backup operation, which avoids excessive requests made to your App Configuration stores.

显示应用程序配置存储区备份体系结构的图表。

资源预配Resource provisioning

备份应用程序配置存储区背后的动机是在不同 Azure 区域中使用多个配置存储区,以提高应用程序的异地复原能力。The motivation behind backing up App Configuration stores is to use multiple configuration stores across different Azure regions to increase the geo-resiliency of your application. 为此,主存储和辅助存储应在不同的 Azure 区域中。To achieve this, your primary and secondary stores should be in different Azure regions. 本教程中创建的所有其他资源可在你选择的任何区域进行预配。All other resources created in this tutorial can be provisioned in any region of your choice. 这是因为,如果主要区域关闭,便没有需要备份的新数据,直到主要区域再次可以访问。This is because if primary region is down, there will be nothing new to back up until the primary region is accessible again.

在本教程中,你将在 chinanorth2 区域创建辅助存储,并在 chinaeast2 区域创建所有其他资源。In this tutorial, you'll create a secondary store in the chinanorth2 region and all other resources in the chinaeast2 region.

如果没有 Azure 试用版订阅,请在开始前创建一个试用版订阅If you don't have an Azure trail subscription, create a trial subscription before you begin..如果没有 Azure 试用版订阅,请在开始前创建一个试用版订阅If you don't have an Azure trail subscription, create a trial subscription before you begin..

必备条件Prerequisites

  • 如果需要,请安装 Azure CLI 来运行 CLI 参考命令。If you prefer, install the Azure CLI to run CLI reference commands.

    • 如果使用的是本地安装,请使用 az login 命令登录到 Azure CLI。If you're using a local installation, sign in to the Azure CLI by using the az login command. 若要完成身份验证过程,请遵循终端中显示的步骤。To finish the authentication process, follow the steps displayed in your terminal. 有关其他登录选项,请参阅登录 Azure CLIFor additional sign-in options, see Sign in with the Azure CLI.

    • 出现提示时,请在首次使用时安装 Azure CLI 扩展。When you're prompted, install Azure CLI extensions on first use. 有关扩展详细信息,请参阅使用 Azure CLI 的扩展For more information about extensions, see Use extensions with the Azure CLI.

    • 运行 az version 以查找安装的版本和依赖库。Run az version to find the version and dependent libraries that are installed. 若要升级到最新版本,请运行 az upgradeTo upgrade to the latest version, run az upgrade.

  • 本教程需要 Azure CLI 2.3.1 或更高版本。This tutorial requires version 2.3.1 or later of the Azure CLI.

创建资源组Create a resource group

该资源组是在其中部署和管理 Azure 资源的逻辑集合。The resource group is a logical collection into which Azure resources are deployed and managed.

使用 az group create 命令创建资源组。Create a resource group by using the az group create command.

以下示例在 chinaeast2 位置创建名为 <resource_group_name> 的资源组。The following example creates a resource group named <resource_group_name> in the chinaeast2 location. <resource_group_name> 替换为资源组的唯一名称。Replace <resource_group_name> with a unique name for your resource group.

resourceGroupName="<resource_group_name>"
az group create --name $resourceGroupName --location chinaeast2

创建应用程序配置存储区Create App Configuration stores

在不同区域创建主应用程序配置和辅助应用程序配置存储区。Create your primary and secondary App Configuration stores in different regions. <primary_appconfig_name><secondary_appconfig_name> 替换为配置存储的唯一名称。Replace <primary_appconfig_name> and <secondary_appconfig_name> with unique names for your configuration stores. 每个存储名称必须唯一,因为它将用作 DNS 名称。Each store name must be unique because it's used as a DNS name.

primaryAppConfigName="<primary_appconfig_name>"
secondaryAppConfigName="<secondary_appconfig_name>"
az appconfig create \
  --name $primaryAppConfigName \
  --location chinaeast2 \
  --resource-group $resourceGroupName\
  --sku standard

az appconfig create \
  --name $secondaryAppConfigName \
  --location chinanorth2 \
  --resource-group $resourceGroupName\
  --sku standard

创建队列Create a queue

创建存储帐户和队列,用于接收事件网格发布的事件。Create a storage account and a queue for receiving the events published by Event Grid.

storageName="<unique_storage_name>"
queueName="<queue_name>"
az storage account create -n $storageName -g $resourceGroupName -l chinaeast2 --sku Standard_LRS
az storage queue create --name $queueName --account-name $storageName --auth-mode login

启用事件网格资源提供程序Enable Event Grid resource provider

如果以前未在 Azure 订阅中使用过事件网格,则可能需要注册事件网格资源提供程序。If you haven't previously used Event Grid in your Azure subscription, you may need to register the Event Grid resource provider. 运行以下命令,注册提供程序:Run the following command to register the provider:

az provider register --namespace Microsoft.EventGrid

完成注册可能需要一些时间。It may take a moment for the registration to finish. 若要检查状态,请运行:To check the status, run:

az provider show --namespace Microsoft.EventGrid --query "registrationState"

registrationStateRegistered 后,即可继续。When registrationState is Registered, you're ready to continue.

订阅应用程序配置存储区事件Subscribe to your App Configuration store events

从主应用程序配置存储区订阅以下两个事件:You subscribe to these two events from the primary App Configuration store:

  • Microsoft.AppConfiguration.KeyValueModified
  • Microsoft.AppConfiguration.KeyValueDeleted

以下命令为发送到队列的两个事件创建事件网格订阅。The following command creates an Event Grid subscription for the two events sent to your queue. 将终结点类型设置为 storagequeue,并将终结点设置为队列 ID。The endpoint type is set to storagequeue, and the endpoint is set to the queue ID. <event_subscription_name> 替换为你为事件订阅选择的名称。Replace <event_subscription_name> with the name of your choice for the event subscription.

storageId=$(az storage account show --name $storageName --resource-group  $resourceGroupName --query id --output tsv)
queueId="$storageId/queueservices/default/queues/$queueName"
appconfigId=$(az appconfig show --name $primaryAppConfigName --resource-group $resourceGroupName --query id --output tsv)
eventSubscriptionName="<event_subscription_name>"
az eventgrid event-subscription create \
  --source-resource-id $appconfigId \
  --name $eventSubscriptionName \
  --endpoint-type storagequeue \
  --endpoint $queueId \
  --included-event-types Microsoft.AppConfiguration.KeyValueModified Microsoft.AppConfiguration.KeyValueDeleted 

创建用于从队列存储处理事件的函数Create functions for handling events from Queue storage

通过现成的函数进行设置Set up with ready-to-use functions

在本文中,你将使用具有以下属性的 C# 函数:In this article, you'll work with C# functions that have the following properties:

  • 运行时堆栈 .NET Core 3.1Runtime stack .NET Core 3.1
  • Azure Functions 运行版本 3.xAzure Functions runtime version 3.x
  • 计时器每 10 分钟触发一次的函数Function triggered by timer every 10 minutes

为了让你能够轻松开始备份数据,我们已测试并发布了一个函数,你无需对代码做出任何更改即可使用。To make it easier for you to start backing up your data, we've tested and published a function that you can use without making any changes to the code. 下载项目文件,并将其从 Visual Studio 发布到自己的 Azure 函数应用Download the project files and publish them to your own Azure function app from Visual Studio.

重要

不要对下载的代码中的环境变量进行任何更改。Don't make any changes to the environment variables in the code you've downloaded. 你将在下一部分中创建所需的应用设置。You'll create the required app settings in the next section.

构建自己的函数Build your own function

如果之前提供的示例代码不符合你的要求,你还可以创建自己的函数。If the sample code provided earlier doesn't meet your requirements, you can also create your own function. 函数必须能够执行以下任务才能完成备份:Your function must be able to perform the following tasks in order to complete the backup:

  • 定期读取队列的内容,以查看其是否包含来自事件网格的任何通知。Periodically read contents of your queue to see if it contains any notifications from Event Grid. 有关实现的详细信息,请参阅存储队列 SDKRefer to the Storage Queue SDK for implementation details.
  • 如果队列包含事件网格中的事件通知,从事件信息中提取唯一的 <key, label> 信息。If your queue contains event notifications from Event Grid, extract all the unique <key, label> information from event messages. 键和标签的组合是主存储中“键值更改”的唯一标识符。The combination of key and label is the unique identifier for key-value changes in the primary store.
  • 从主存储读取所有设置。Read all settings from the primary store. 仅更新辅助存储中在队列中具有相应事件的设置。Update only those settings in the secondary store that have a corresponding event in the queue. 从辅助存储中删除在队列中存在但主存储中不存在的所有设置。Delete all settings from the secondary store that were present in the queue but not in the primary store. 可以使用应用程序配置 SDK 以编程方式访问配置存储区。You can use the App Configuration SDK to access your configuration stores programmatically.
  • 如果处理过程中没有异常,从队列中删除消息。Delete messages from the queue if there were no exceptions during processing.
  • 根据需要实现错误处理。Implement error handling according to your needs. 请参阅前面的代码示例,查看你可能想要处理的一些常见异常。Refer to the preceding code sample to see some common exceptions that you might want to handle.

若要详细了解创建一个函数,请参阅:在 Azure 中创建由计时器触发的函数使用 Visual Studio 开发 Azure FunctionsTo learn more about creating a function, see: Create a function in Azure that is triggered by a timer and Develop Azure Functions using Visual Studio.

重要

使用最佳判断根据主配置存储区的更改频率选择计时器计划。Use your best judgement to choose the timer schedule based on how often you make changes to your primary configuration store. 过于频繁地运行该函数可能会限制对存储的请求。Running the function too often might end up throttling requests for your store.

创建函数应用设置Create function app settings

如果你使用的是我们提供的功能,则需要在函数应用中配置以下应用设置:If you're using a function that we've provided, you need the following app settings in your function app:

  • PrimaryStoreEndpoint:主应用程序配置存储区的终结点。PrimaryStoreEndpoint: Endpoint for the primary App Configuration store. 例如 https://{primary_appconfig_name}.azconfig.ioAn example is https://{primary_appconfig_name}.azconfig.io.
  • SecondaryStoreEndpoint:辅助应用程序配置存储区的终结点。SecondaryStoreEndpoint: Endpoint for the secondary App Configuration store. 例如 https://{secondary_appconfig_name}.azconfig.ioAn example is https://{secondary_appconfig_name}.azconfig.io.
  • StorageQueueUri:队列 URI。StorageQueueUri: Queue URI. 例如 https://{unique_storage_name}.queue.core.chinacloudapi.cn/{queue_name}An example is https://{unique_storage_name}.queue.core.chinacloudapi.cn/{queue_name}.

以下命令在函数应用中创建所需的应用设置。The following command creates the required app settings in your function app. <function_app_name> 替换为你的函数应用的名称。Replace <function_app_name> with the name of your function app.

functionAppName="<function_app_name>"
primaryStoreEndpoint="https://$primaryAppConfigName.azconfig.io"
secondaryStoreEndpoint="https://$secondaryAppConfigName.azconfig.io"
storageQueueUri="https://$storageName.queue.core.chinacloudapi.cn/$queueName"
az functionapp config appsettings set --name $functionAppName --resource-group $resourceGroupName --settings StorageQueueUri=$storageQueueUri PrimaryStoreEndpoint=$primaryStoreEndpoint SecondaryStoreEndpoint=$secondaryStoreEndpoint

向函数应用的托管标识授予访问权限Grant access to the managed identity of the function app

使用以下命令或 Azure 门户为函数应用添加系统分配的托管标识。Use the following command or the Azure portal to add a system-assigned managed identity for your function app.

az functionapp identity assign --name $functionAppName --resource-group $resourceGroupName

备注

要执行所需的资源创建和角色管理,帐户在相应的范围(订阅或资源组)需要 Owner 权限。To perform the required resource creation and role management, your account needs Owner permissions at the appropriate scope (your subscription or resource group). 如果需有关要角色分配的帮助,请了解如何使用 Azure 门户添加或删除 Azure 角色分配If you need assistance with role assignment, learn how to add or remove Azure role assignments by using the Azure portal.

使用以下命令或 Azure 门户向函数应用的托管标识授予对应用程序配置存储区的访问权限。Use the following commands or the Azure portal to grant the managed identity of your function app access to your App Configuration stores. 使用以下角色:Use these roles:

  • 分配主应用程序配置存储区中的 App Configuration Data Reader 角色。Assign the App Configuration Data Reader role in the primary App Configuration store.
  • 在辅助应用程序配置存储区分配 App Configuration Data Owner 角色。Assign the App Configuration Data Owner role in the secondary App Configuration store.
functionPrincipalId=$(az functionapp identity show --name $functionAppName --resource-group  $resourceGroupName --query principalId --output tsv)
primaryAppConfigId=$(az appconfig show -n $primaryAppConfigName --query id --output tsv)
secondaryAppConfigId=$(az appconfig show -n $secondaryAppConfigName --query id --output tsv)

az role assignment create \
    --role "App Configuration Data Reader" \
    --assignee $functionPrincipalId \
    --scope $primaryAppConfigId

az role assignment create \
    --role "App Configuration Data Owner" \
    --assignee $functionPrincipalId \
    --scope $secondaryAppConfigId

使用以下命令或 Azure 门户向函数应用的托管标识授予对队列的访问权限。Use the following command or the Azure portal to grant the managed identity of your function app access to your queue. 在队列中分配 Storage Queue Data Contributor 角色。Assign the Storage Queue Data Contributor role in the queue.

az role assignment create \
    --role "Storage Queue Data Contributor" \
    --assignee $functionPrincipalId \
    --scope $queueId

触发应用程序配置事件Trigger an App Configuration event

若要测试所有功能是否正常运行,可以从主存储创建、更新或删除键值。To test that everything works, you can create, update, or delete a key-value from the primary store. 在计时器触发 Azure Functions 几秒钟后,辅助存储中会自动显示此更改。You should automatically see this change in the secondary store a few seconds after the timer triggers Azure Functions.

az appconfig kv set --name $primaryAppConfigName --key Foo --value Bar --yes

你已触发了该事件。You've triggered the event. 几分钟后,事件网格会将事件通知发送到你的队列。In a few moments, Event Grid will send the event notification to your queue. 在下次按计划运行函数后,查看辅助存储中的配置设置,以查看它是否包含主存储中更新的键值。After the next scheduled run of your function, view configuration settings in your secondary store to see if it contains the updated key-value from the primary store.

备注

可以在测试和故障排除期间手动触发函数,而无需等待计划的计数器触发。You can trigger your function manually during the testing and troubleshooting without waiting for the scheduled timer-trigger.

确保备份函数成功运行后,可以看到辅助存储中现在有了该键。After you make sure that the backup function ran successfully, you can see that the key is now present in your secondary store.

az appconfig kv show --name $secondaryAppConfigName --key Foo
{
  "contentType": null,
  "etag": "eVgJugUUuopXnbCxg0dB63PDEJY",
  "key": "Foo",
  "label": null,
  "lastModified": "2020-04-27T23:25:08+00:00",
  "locked": false,
  "tags": {},
  "value": "Bar"
}

故障排除Troubleshooting

如果在辅助存储中看不到新设置:If you don't see the new setting in your secondary store:

  • 在主存储中创建设置后,确保触发了备份函数。Make sure the backup function was triggered after you created the setting in your primary store.
  • 事件网格可能无法及时将事件通知发送到队列。It's possible that Event Grid couldn't send the event notification to the queue in time. 查看队列是否仍包含来自主存储的事件通知。Check if your queue still contains the event notification from your primary store. 如果是,请再次触发备份函数。If it does, trigger the backup function again.
  • 查看 Azure Functions 日志中是否记录了任何错误或警告。Check Azure Functions logs for any errors or warnings.
  • 使用 Azure 门户可确保 Azure 函数应用包含 Azure Functions 正在尝试读取的应用程序设置的正确值。Use the Azure portal to ensure that the Azure function app contains correct values for the application settings that Azure Functions is trying to read.
  • 还可以使用 Azure Application Insights 为 Azure Functions 设置监视和警报。You can also set up monitoring and alerting for Azure Functions by using Azure Application Insights.

清理资源Clean up resources

如果你打算继续使用此应用程序配置和事件订阅,请不要清理在本文中创建的资源。If you plan to continue working with this App Configuration and event subscription, don't clean up the resources created in this article. 如果不打算继续学习,请使用以下命令删除本文中创建的资源。If you don't plan to continue, use the following command to delete the resources created in this article.

az group delete --name $resourceGroupName

后续步骤Next steps

现在你已了解如何设置键值的自动备份,请详细了解如何提高应用程序的异地复原能力:Now that you know how to set up automatic backup of your key-values, learn more about how you can increase the geo-resiliency of your application: