使用 Azure App Configuration 实现动态配置
Source: Dev.to

Azure App Configuration 提供了一项服务,用于集中管理应用程序设置和功能标记。现代程序,尤其是在云中运行的程序,通常由许多分布式组件组成。
在本文中,我们将探讨使用 Azure App Configuration 的动态配置以及标签如何进一步提升动态化程度。通过标签,您可以在一个位置为特定环境提供设置,同时使用环境变量来获取各环境的值。您还可以使用标签创建不同的配置文件——只需使用不同的键而不是环境名称即可。
Calling label‑specific configurations with .NET
First, add the package Microsoft.Extensions.Configuration.AzureAppConfiguration:
dotnet add package Microsoft.Extensions.Configuration.AzureAppConfiguration
Configure the connection to Azure App Configuration using an environment variable that holds the connection string:
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddAzureAppConfiguration(options => {
options.Connect(builder.Configuration.GetConnectionString("APPCONFIG_CONNECTION_STRING"))
.Select(KeyFilter.Any, LabelFilter.Null) // Load unlabelled settings
.Select(KeyFilter.Any, ""); // Load settings with a specific label
});
The first Select loads all configurations without a label; the second loads those with the specified label.
For an environment‑based approach, you can use the current environment name:
var environment = builder.Environment.EnvironmentName;
Your configuration settings are then accessed through the normal IConfiguration interface.
You can also supply any label name (e.g., from a database or Redis cache) in the Select method to load a specific profile.
Calling label‑specific configurations with TypeScript
The same principles apply when using the JavaScript SDK, which works with React, Angular, etc. Install the package via npm:
npm install @azure/app-configuration
Import the client in your TypeScript file:
import { AppConfigurationClient } from "@azure/app-configuration";
Set up connection variables and the key you want to retrieve:
const connectionString = process.env["APPCONFIG_CONNECTION_STRING"] || "";
const client = new AppConfigurationClient(connectionString);
const configKey = "Samples:Endpoint:Url";
const labelKey = process.env["ENVIRONMENT"] || "Development";
Retrieve the configuration setting using the key and label:
const betaEndpoint = await client.getConfigurationSetting({
key: configKey,
label: labelKey
});