快速入门:使用 Azure 应用程序配置创建 Node.js 控制台应用
在本快速入门中,你将使用 Azure 应用程序配置 JavaScript 提供程序客户端库通过 Azure 应用程序配置来集中存储和管理应用程序设置。
适用于 JavaScript 的应用程序配置提供程序基于 Azure SDK for JavaScript 构建,旨在更轻松地用于更丰富的功能。
它允许以 Map
对象的形式访问应用程序配置中的键值。
它提供了从多个标签组合配置、密钥前缀剪裁、Key Vault 引用自动解析等功能。
作为示例,本教程演示如何在 Node.js 应用中使用 JavaScript 提供程序。
- 具有活动订阅的 Azure 帐户。 创建试用版订阅。
- 应用程序配置存储区。 创建存储区。
- LTS 版本的 Node.js。 有关直接在 Windows 上或使用适用于 Linux 的 Windows 子系统 (WSL) 安装 Node.js 的信息,请参阅 Node.js 入门
将以下键值添加到应用程序配置存储区。 有关如何使用 Azure 门户或 CLI 将键值添加到存储区的详细信息,请转到创建键值。
密钥 | 值 | 内容类型 |
---|---|---|
message | 来自 Azure 应用程序配置的消息 | 留空 |
app.greeting | Hello World | 留空 |
app.json | {"myKey":"myValue"} | application/json |
在本教程中,你将创建一个 Node.js 控制台应用并从你的应用程序配置存储中加载数据。
为名为 app-configuration-quickstart 的项目创建一个新目录。
mkdir app-configuration-quickstart
切换到新创建的 app-configuration-quickstart 目录。
cd app-configuration-quickstart
使用
npm install
命令安装 Azure 应用配置提供程序。npm install @azure/app-configuration-provider
以下示例演示如何从 Azure 应用程序配置检索配置数据并在应用程序中使用它。
默认情况下,键值作为 Map
对象加载,允许你使用完整键名访问每个键值。
但是,如果应用程序使用配置对象,则可以使用 constructConfigurationObject
帮助程序 API,该 API 根据从 Azure 应用程序配置加载的键值创建配置对象。
在 app-configuration-quickstart 目录中创建名为 app.js 的文件,并从每个示例复制代码。
在此示例中,将连接到 Azure 应用程序配置并加载键值,而无需指定高级选项。 默认情况下,它会加载所有不带标签的键值。 可以使用 Microsoft Entra ID(建议)或连接字符串连接到应用程序配置存储区。
可以使用 DefaultAzureCredential
向应用程序配置存储区进行身份验证。 按照说明为凭据分配应用程序配置数据读取者角色。 在运行应用程序之前,请务必留出足够的时间来传播权限。
const { load } = require("@azure/app-configuration-provider");
const { DefaultAzureCredential } = require("@azure/identity");
const endpoint = process.env.AZURE_APPCONFIG_ENDPOINT;
const credential = new DefaultAzureCredential(); // For more information, see https://learn.microsoft.com/azure/developer/javascript/sdk/credential-chains#use-defaultazurecredential-for-flexibility
async function run() {
console.log("Sample 1: Load key-values with default selector");
// Connect to Azure App Configuration using a token credential and load all key-values with null label.
const settings = await load(endpoint, credential);
console.log("---Consume configuration as a Map---");
// Find the key "message" and print its value.
console.log('settings.get("message"):', settings.get("message")); // settings.get("message"): Message from Azure App Configuration
// Find the key "app.greeting" and print its value.
console.log('settings.get("app.greeting"):', settings.get("app.greeting")); // settings.get("app.greeting"): Hello World
// Find the key "app.json" whose value is an object.
console.log('settings.get("app.json"):', settings.get("app.json")); // settings.get("app.json"): { myKey: 'myValue' }
console.log("---Consume configuration as an object---");
// Construct configuration object from loaded key-values, by default "." is used to separate hierarchical keys.
const config = settings.constructConfigurationObject();
// Use dot-notation to access configuration
console.log("config.message:", config.message); // config.message: Message from Azure App Configuration
console.log("config.app.greeting:", config.app.greeting); // config.app.greeting: Hello World
console.log("config.app.json:", config.app.json); // config.app.json: { myKey: 'myValue' }
}
run().catch(console.error);
在此示例中,将通过指定 selectors
选项来加载键值的子集。
仅加载以“app.”开头的键。
请注意,可以根据需求指定多个选择器,每个选择器都具有 keyFilter
和 labelFilter
属性。
const { load } = require("@azure/app-configuration-provider");
const { DefaultAzureCredential } = require("@azure/identity");
const endpoint = process.env.AZURE_APPCONFIG_ENDPOINT;
const credential = new DefaultAzureCredential(); // For more information, see https://learn.microsoft.com/azure/developer/javascript/sdk/credential-chains#use-defaultazurecredential-for-flexibility
async function run() {
console.log("Sample 2: Load specific key-values using selectors");
// Load a subset of keys starting with "app." prefix.
const settings = await load(endpoint, credential, {
selectors: [{
keyFilter: "app.*"
}],
});
console.log("---Consume configuration as a Map---");
// The key "message" is not loaded as it does not start with "app."
console.log('settings.has("message"):', settings.has("message")); // settings.has("message"): false
// The key "app.greeting" is loaded
console.log('settings.has("app.greeting"):', settings.has("app.greeting")); // settings.has("app.greeting"): true
// The key "app.json" is loaded
console.log('settings.has("app.json"):', settings.has("app.json")); // settings.has("app.json"): true
console.log("---Consume configuration as an object---");
// Construct configuration object from loaded key-values
const config = settings.constructConfigurationObject({ separator: "." });
// Use dot-notation to access configuration
console.log("config.message:", config.message); // config.message: undefined
console.log("config.app.greeting:", config.app.greeting); // config.app.greeting: Hello World
console.log("config.app.json:", config.app.json); // config.app.json: { myKey: 'myValue' }
}
run().catch(console.error);
在此示例中,将使用选项 trimKeyPrefixes
加载键值。
加载键值后,将从所有键中剪裁前缀“app.”。
如果希望通过筛选特定键前缀来加载特定于应用程序的配置,但不希望代码每次访问配置时都携带该前缀,此功能非常有用。
const { load } = require("@azure/app-configuration-provider");
const { DefaultAzureCredential } = require("@azure/identity");
const endpoint = process.env.AZURE_APPCONFIG_ENDPOINT;
const credential = new DefaultAzureCredential(); // For more information, see https://learn.microsoft.com/azure/developer/javascript/sdk/credential-chains#use-defaultazurecredential-for-flexibility
async function run() {
console.log("Sample 3: Load key-values and trim prefix from keys");
// Load all key-values with no label, and trim "app." prefix from all keys.
const settings = await load(endpoint, credential, {
selectors: [{
keyFilter: "app.*"
}],
trimKeyPrefixes: ["app."]
});
console.log("---Consume configuration as a Map---");
// The original key "app.greeting" is trimmed as "greeting".
console.log('settings.get("greeting"):', settings.get("greeting")); // settings.get("greeting"): Hello World
// The original key "app.json" is trimmed as "json".
console.log('settings.get("json"):', settings.get("json")); // settings.get("json"): { myKey: 'myValue' }
console.log("---Consume configuration as an object---");
// Construct configuration object from loaded key-values with trimmed keys.
const config = settings.constructConfigurationObject();
// Use dot-notation to access configuration
console.log("config.greeting:", config.greeting); // config.greeting: Hello World
console.log("config.json:", config.json); // config.json: { myKey: 'myValue' }
}
run()
设置 环境变量。
将名为 AZURE_APPCONFIG_ENDPOINT 的环境变量设置为 Azure 门户中存储区的“概述”下的应用程序配置存储区的终结点。
如果使用 Windows 命令提示符,则请运行以下命令并重启命令提示符,这样更改才会生效:
setx AZURE_APPCONFIG_ENDPOINT "<endpoint-of-your-app-configuration-store>"
如果使用 PowerShell,请运行以下命令:
$Env:AZURE_APPCONFIG_ENDPOINT = "<endpoint-of-your-app-configuration-store>"
如果使用 macOS 或 Linux,则请运行以下命令:
export AZURE_APPCONFIG_ENDPOINT='<endpoint-of-your-app-configuration-store>'
正确设置环境变量后,请运行以下命令以在本地运行应用:
node app.js
对于每个示例,你应该看到以下输出:
示例 1
Sample 1: Load key-values with default selector ---Consume configuration as a Map--- settings.get("message"): Message from Azure App Configuration settings.get("app.greeting"): Hello World settings.get("app.json"): { myKey: 'myValue' } ---Consume configuration as an object--- config.message: Message from Azure App Configuration config.app.greeting: Hello World config.app.json: { myKey: 'myValue' }
示例 2
Sample 2: Load specific key-values using selectors ---Consume configuration as a Map--- settings.has("message"): false settings.has("app.greeting"): true settings.has("app.json"): true ---Consume configuration as an object--- config.message: undefined config.app.greeting: Hello World config.app.json: { myKey: 'myValue' }
示例 3
Sample 3: Load key-values and trim prefix from keys ---Consume configuration as a Map--- settings.get("greeting"): Hello World settings.get("json"): { myKey: 'myValue' } ---Consume configuration as an object--- config.greeting: Hello World config.json: { myKey: 'myValue' }
如果不想继续使用本文中创建的资源,请删除此处创建的资源组以避免产生费用。
重要
删除资源组的操作不可逆。 将永久删除资源组以及其中的所有资源。 请确保不要意外删除错误的资源组或资源。 如果在包含要保留的其他资源的资源组中创建了本文的资源,请从相应的窗格中单独删除每个资源,而不是删除该资源组。
- 登录到 Azure 门户,然后选择“资源组”。
- 在“按名称筛选”框中,输入资源组的名称。
- 在结果列表中,选择资源组名称以查看概述。
- 选择“删除资源组”。
- 系统会要求确认是否删除资源组。 重新键入资源组的名称进行确认,然后选择“删除”。
片刻之后,将会删除该资源组及其所有资源。
在本快速入门中,你创建了一个新的应用程序配置存储,并学习了如何在 Node.js 应用中使用应用程序配置 JavaScript 提供程序访问键值。 若要了解如何配置应用来动态刷新配置设置,请继续学习下一个教程。