你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 JavaScript 的应用配置客户端库

Azure 应用配置 是一项托管服务,可帮助开发人员简单安全地集中其应用程序和功能设置。

使用应用配置的客户端库可以:

  • 创建灵活的密钥表示形式和映射
  • 使用标签标记键
  • 从任何时间点重播设置
  • 管理应用配置的快照

关键链接:

开始

安装包

npm install @azure/app-configuration

当前支持的环境

有关详细信息,请参阅我们的 支持策略

先决条件

创建应用配置资源

可以使用 Azure 门户Azure CLI 来创建 Azure 应用配置资源。

示例(Azure CLI):

az appconfig create --name <app-configuration-resource-name> --resource-group <resource-group-name> --location eastus

对客户端进行身份验证

AppConfigurationClient 可以使用 服务主体 或使用 连接字符串进行身份验证。

使用服务主体进行身份验证

通过服务主体进行身份验证的方法是:

  • 使用 @azure/identity 包创建凭据。
  • 在 AppConfiguration 资源上设置适当的 RBAC 规则。 可在此处找到有关应用配置角色的详细信息。

使用 DefaultAzureCredential

const azureIdentity = require("@azure/identity");
const appConfig = require("@azure/app-configuration");

const credential = new azureIdentity.DefaultAzureCredential();
const client = new appConfig.AppConfigurationClient(
  endpoint, // ex: <https://<your appconfig resource>.azconfig.io>
  credential
);

可在此处 找到有关 的详细信息

主权云

若要使用 Sovereign Cloud中的资源进行身份验证,需要在凭据选项中或通过 AZURE_AUTHORITY_HOST 环境变量设置 authorityHost

const { AppConfigurationClient } = require("@azure/app-configuration");
const { DefaultAzureCredential, AzureAuthorityHosts } = require("@azure/identity");

// Create an AppConfigurationClient that will authenticate through AAD in the China cloud
const client = new AppConfigurationClient(
  endpoint, // ex: <https://<your appconfig resource>.azconfig.azure.cn>
  new DefaultAzureCredential({ authorityHost: AzureAuthorityHosts.AzureChina })
);

可在此处 找到有关 的详细信息

使用连接字符串进行身份验证

若要获取应用配置资源的主 连接字符串,可以使用此 Azure CLI 命令:

az appconfig credential list -g <resource-group-name> -n <app-configuration-resource-name> --query "([?name=='Primary'].connectionString)[0]"

在代码中,现在可以使用从 Azure CLI 获取 连接字符串创建应用配置客户端:

const client = new AppConfigurationClient("<connection string>");

关键概念

AppConfigurationClient 在门户中对应用配置进行了一些术语更改。

  • 键/值对表示为 ConfigurationSetting 对象
  • 锁定和解锁设置在 isReadOnly 字段中表示,可以使用 setReadOnly进行切换。
  • 快照表示为 ConfigurationSnapshot 对象。

客户端遵循简单的设计方法 - ConfigurationSetting 可以传递到采用 ConfigurationSettingParamConfigurationSettingId的任何方法中。

这意味着此模式有效:

const setting = await client.getConfigurationSetting({
  key: "hello"
});

setting.value = "new value!";
await client.setConfigurationSetting(setting);

// fields unrelated to just identifying the setting are simply
// ignored (for instance, the `value` field)
await client.setReadOnly(setting, true);

// delete just needs to identify the setting so other fields are
// just ignored
await client.deleteConfigurationSetting(setting);

或者,例如,重新获取设置:

let setting = await client.getConfigurationSetting({
  key: "hello"
});

// re-get the setting
setting = await client.getConfigurationSetting(setting);

2022-11-01-preview API 版本支持配置快照:配置存储的不可变时间点副本。 可以使用筛选器创建快照,以确定快照中包含的键值对、创建配置存储的不可变组合视图。 此功能使应用程序能够保持一致的配置视图,确保在进行更新时读取各个设置时没有版本不匹配。 例如,此功能可用于在应用配置中创建“发布配置快照”。 请参阅以下示例 创建和获取快照 部分

例子

创建和获取设置

const appConfig = require("@azure/app-configuration");

const client = new appConfig.AppConfigurationClient(
  "<App Configuration connection string goes here>"
);

async function run() {
  const newSetting = await client.setConfigurationSetting({
    key: "testkey",
    value: "testvalue",
    // Labels allow you to create variants of a key tailored
    // for specific use-cases like supporting multiple environments.
    // /azure/azure-app-configuration/concept-key-value#label-keys
    label: "optional-label"
  });

  const retrievedSetting = await client.getConfigurationSetting({
    key: "testkey",
    label: "optional-label"
  });

  console.log("Retrieved value:", retrievedSetting.value);
}

run().catch((err) => console.log("ERROR:", err));

创建快照

beginCreateSnapshot 提供轮询程序来轮询快照创建。

const { AppConfigurationClient } = require("@azure/app-configuration");

const client = new AppConfigurationClient(
  "<App Configuration connection string goes here>"
);


async function run() {
  const key = "testkey";
  const value = "testvalue";
  const label = "optional-label";

  await client.addConfigurationSetting({
    key,
    value,
    label
  });

  const poller = await client.beginCreateSnapshot({
    name:"testsnapshot",
    retentionPeriod: 2592000,
    filters: [{keyFilter: key, labelFilter: label}],
  });
  const snapshot = await poller.pollUntilDone();
}

run().catch((err) => console.log("ERROR:", err));

还可以使用 beginCreateSnapshotAndWait 在轮询完成后直接创建结果。

const snapshot  = await client.beginCreateSnapshotAndWait({
  name:"testsnapshot",
  retentionPeriod: 2592000,
  filters: [{keyFilter: key, labelFilter: label}],
});

获取快照

const retrievedSnapshot = await client.getSnapshot("testsnapshot");
console.log("Retrieved snapshot:", retrievedSnapshot);

列出快照中的 ConfigurationSetting

const retrievedSnapshotSettings = await client.listConfigurationSettingsForSnapshot("testsnapshot");

for await (const setting of retrievedSnapshotSettings) {
  console.log(`Found key: ${setting.key}, label: ${setting.label}`);
}

列出服务中的所有快照

const snapshots = await client.listSnapshots();

for await (const snapshot of snapshots) {
  console.log(`Found snapshot: ${snapshot.name}`);
}

恢复和存档快照

// Snapshot is in ready status
const archivedSnapshot = await client.archiveSnapshot("testsnapshot");
console.log("Snapshot updated status is:", archivedSnapshot.status);

// Snapshot is in archive status
const recoverSnapshot = await client.recoverSnapshot("testsnapshot");
console.log("Snapshot updated status is:", recoverSnapshot.status);

故障 排除

伐木

启用日志记录可能有助于发现有关故障的有用信息。 若要查看 HTTP 请求和响应的日志,请将 AZURE_LOG_LEVEL 环境变量设置为 info。 或者,可以通过在 @azure/logger中调用 setLogLevel 在运行时启用日志记录:

const { setLogLevel } = require("@azure/logger");

setLogLevel("info");

有关如何启用日志的更详细说明,可以查看 @azure/记录器包文档

React Native 支持

React Native 不支持此 SDK 库使用的一些 JavaScript API,因此你需要为它们提供填充。 有关详细信息,请参阅我们的 React Native 示例和 Expo

后续步骤

以下示例演示了与应用配置交互的各种方式:

可以在 GitHub 上的 示例 文件夹中找到更深入的示例。

贡献

若要参与此库,请阅读 贡献指南 了解有关如何生成和测试代码的详细信息。

本模块的测试是实时测试和单元测试的混合体,这要求你拥有 Azure 应用配置实例。 若要执行测试,需要运行:

  1. rush update
  2. rush build -t @azure/app-configuration
  3. sdk\appconfiguration\app-configuration 文件夹中创建包含以下内容的 .env 文件:APPCONFIG_CONNECTION_STRING=connection string for your App Configuration instance
  4. cd sdk\appconfiguration\app-configuration
  5. npm run test

有关详细信息,请查看 测试 文件夹。

印象