다음을 통해 공유


JavaScript 구성 공급자

configuration-provider-npm-package

Azure 앱 Configuration은 개발자가 애플리케이션 구성을 간단하고 안전하게 중앙 집중화하는 데 도움이 되는 관리형 서비스입니다. JavaScript 구성 공급자 라이브러리를 사용하면 관리되는 방식으로 Azure 앱 Configuration 저장소에서 구성을 로드할 수 있습니다. 이 클라이언트 라이브러리는 JavaScript용 Azure SDK 위에 추가 기능을 추가합니다.

구성 로드

load 패키지에서 @azure/app-configuration-provider 내보낸 메서드는 Azure 앱 구성에서 구성을 로드하는 데 사용됩니다. 이 load 메서드를 사용하면 Microsoft Entra ID를 사용하거나 연결 문자열 App Configuration 저장소에 연결할 수 있습니다.

App Configuration 저장소에 인증하는 데 사용합니다 DefaultAzureCredential . 지침에 따라 자격 증명에 App Configuration 데이터 읽기 역할을 할당합니다.

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() {
    // Connect to Azure App Configuration using a token credential and load all key-values with no label.
    const appConfig = await load(endpoint, credential);
    console.log('appConfig.get("message"):', appConfig.get("message"));
}

run();

메서드는 load 다음과 같이 정의된 형식의 AzureAppConfiguration 인스턴스를 반환합니다.

type AzureAppConfiguration = {
    refresh(): Promise<void>;
    onRefresh(listener: () => any, thisArg?: any): Disposable;
} & IGettable & ReadonlyMap<string, any> & IConfigurationObject;

방법에 대한 refreshonRefresh 자세한 내용은 구성 새로 고침 섹션을 참조하세요.

구성 사용

형식은 AzureAppConfiguration 다음 인터페이스를 확장합니다.

  • IGettable

    interface IGettable {
        get<T>(key: string): T | undefined;
    }
    

    인터페이스는 IGettable 지도 스타일 데이터 구조에서 키-값의 값을 검색하는 메서드를 제공합니다 get .

    const appConfig = await load(endpoint, credential);
    const fontSize = appConfig.get("app:font:size"); // value of the key "app:font:size" from the App Configuration store
    
  • ReadonlyMap

    또한 이 형식은 AzureAppConfiguration 인터페이스를 ReadonlyMap 확장하여 키-값 쌍에 대한 읽기 전용 액세스를 제공합니다.

  • IConfigurationObject

    interface IConfigurationObject {
        constructConfigurationObject(options?: ConfigurationObjectConstructionOptions): Record<string, any>;
    }
    

    인터페이스는 IConfigurationObject 지도 스타일 데이터 구조 및 계층 키를 기반으로 구성 개체를 생성하는 메서드를 제공합니다 constructConfigurationObject . 선택적 ConfigurationObjectConstructionOptions 매개 변수를 사용하여 계층 키를 개체 속성으로 변환하기 위한 구분 기호를 지정할 수 있습니다. 기본적으로 구분 기호는 .입니다 ".".

    interface ConfigurationObjectConstructionOptions {
        separator?: "." | "," | ";" | "-" | "_" | "__" | "/" | ":"; // supported separators
    }
    

    JavaScript에서 개체 또는 맵은 일반적으로 구성을 나타내는 기본 데이터 구조로 사용됩니다. JavaScript 구성 공급자 라이브러리는 두 가지 구성 방법을 모두 지원하므로 개발자는 필요에 가장 적합한 옵션을 유연하게 선택할 수 있습니다.

    const appConfig = await load(endpoint, credential);
    const settingsObj = appConfig.constructConfigurationObject({separator: ":"});
    const fontSize1 = appConfig.get("app:font:size"); // map-style configuration representation
    const fontSize2 = settingsObj.app.font.size; // object-style configuration representation
    

JSON 콘텐츠 형식 처리

App Configuration에서 JSON 키 값을 만들 수 있습니다. Azure App Configuration에서 키-값을 로드할 때 구성 공급자는 유효한 JSON 콘텐츠 형식(예: application/json)의 키-값을 개체로 자동으로 변환합니다.

{
    "key": "font",
    "label": null,
    "value": "{\r\n\t\"size\": 12,\r\n\t\"color\": \"red\"\r\n}",
    "content_type": "application/json"
}

위의 키-값은 { size: 12, color: "red" }으로 로드됩니다.

const appConfig = await load(endpoint, credential);
const { size, color } = appConfig.get("font");

선택기를 사용하여 특정 키 값 로드

기본적으로 메서드는 load 구성 저장소에서 레이블이 없는 모든 구성을 로드합니다. 형식의 선택적 매개 변수를 load 통해 메서드의 AzureAppConfigurationOptions 동작을 구성할 수 있습니다.

App Configuration 저장소에서 로드된 구성을 구체화하거나 확장하려면 속성 아래에 AzureAppConfigurationOptions.selectors 키 또는 레이블 선택기를 지정할 수 있습니다.

const appConfig = await load(endpoint, credential, {
    selectors: [
        { // load the subset of keys starting with "app1." prefix and "test" label
            keyFilter: "app1.*",
            labelFilter: "test"
        },
        { // load the subset of keys starting with "dev" label"
            labelFilter: "dev*"
        }
    ]
});

참고 항목

키 값은 선택기가 나열되는 순서대로 로드됩니다. 여러 선택기가 동일한 키를 사용하여 키 값을 검색하는 경우 마지막 선택기의 값이 이전에 로드된 값을 재정의합니다.

키에서 접두사 자르기

속성에 트리밍된 키 접두사 목록을 제공하여 키의 접두사를 잘라낼 수 있습니다 AzureAppConfigurationOptions.trimKeyPrefixes .

const appConfig = await load(endpoint, credential, {
    selectors: [{
        keyFilter: "app.*"
    }],
    trimKeyPrefixes: ["app."]
});

구성 새로 고침

구성에 대한 동적 새로 고침을 사용하면 애플리케이션을 다시 시작하지 않고도 App Configuration 저장소에서 최신 값을 끌어올 수 있습니다. 새로 고침을 사용하도록 설정하고 AzureAppConfigurationOptions.refreshOptions 새로 고침 옵션을 구성할 수 있습니다. 서버에서 선택한 키-값의 변경 내용이 검색되면 로드된 구성이 업데이트됩니다. 기본 새로 고침 간격은 30초이지만 refreshIntervalInMs 속성으로 이를 재정의할 수 있습니다.

const appConfig = await load(endpoint, credential, {
    refreshOptions: {
        enabled: true,
        refreshIntervalInMs: 15_000
    }
});

refreshOptions 하나만 설정해도 구성이 자동으로 새로 고쳐지지는 않습니다. 새로 고침을 refresh 트리거하려면 메서드에서 AzureAppConfiguration 반환된 인스턴스에서 load 메서드를 호출해야 합니다.

// this call is not blocking, the configuration will be updated asynchronously
appConfig.refresh();

이 디자인은 애플리케이션이 유휴 상태일 때 App Configuration에 대한 불필요한 요청을 방지합니다. 애플리케이션 활동이 발생하는 refresh 호출을 포함해야 합니다. 이를 활동 기반 구성 새로 고침이라고 합니다. 예를 들어 들어오는 요청을 처리할 때 또는 복잡한 작업을 수행하는 반복 내에서 호출 refresh 할 수 있습니다.

const server = express();
// Use an express middleware to refresh configuration whenever a request comes in
server.use((req, res, next) => {
    appConfig.refresh();
    next();
})

어떤 이유로든 새로 고침 호출이 실패하더라도 애플리케이션은 캐시된 구성을 계속 사용합니다. 구성된 새로 고침 간격이 통과되고 새로 고침 호출이 애플리케이션 활동에 의해 트리거되면 또 다른 시도가 수행됩니다. refresh를 호출하는 것은 구성된 새로 고침 간격이 지나기 전에 작동하지 않으므로 자주 호출하더라도 성능에 미치는 영향은 최소화됩니다.

사용자 지정 새로 고침 콜백

onRefresh 메서드를 사용하면 로컬 구성이 Azure 앱 Configuration 저장소의 변경 내용으로 성공적으로 업데이트될 때마다 호출되는 콜백 함수를 사용자 지정할 수 있습니다. 등록된 콜백을 제거하는 데 사용할 수 있는 Disposable 개체를 반환합니다.

const appConfig = await load(endpoint, credential, {
    refreshOptions: {
        enabled: true
    }
});
const disposer = appConfig.onRefresh(() => {
    console.log("Config refreshed.");
});

appConfig.refresh();
// Once the refresh is successful, the callback function you registered will be executed.
// In this example, the message "Config refreshed" will be printed.

disposer.dispose();

sentinel 키에서 새로 고침

sentinel 키는 다른 모든 키의 변경을 완료한 후 업데이트하는 키입니다. 구성 공급자는 선택한 모든 키 값 대신 sentinel 키를 모니터링합니다. 변경이 감지되면 앱이 모든 구성 값을 새로 고칩니다.

const appConfig = await load(endpoint, credential, {
    refreshOptions: {
        enabled: true,
        watchedSettings: [
            { key: "sentinel" }
        ]
    }
});

새로 고침 구성에 대한 자세한 내용은 JavaScript에서 동적 구성 사용으로 이동하세요.

기능 플래그

Azure App Configuration에서 기능 플래그를 만들 수 있습니다. 기본적으로 기능 플래그는 구성 공급자에 의해 로드되지 않습니다. 메서드를 호출할 때 속성을 통해 AzureAppConfigurationOptions.featureFlagOptions 기능 플래그 로드 및 새로 고침을 load 사용하도록 설정할 수 있습니다.

const appConfig = await load(endpoint, credential, {
    featureFlagOptions: {
        enabled: true, // enable loading feature flags
        selectors: [ { keyFilter: "*", labelFilter: "Prod" } ],
        refresh: {
            enabled: true, // enable refreshing feature flags
            refreshIntervalInMs: 60_000
        }
    }
});

참고 항목

사용하도록 설정되어 있고 선택기가 지정되지 않은 경우 featureFlagOptions 구성 공급자는 App Configuration 저장소에서 레이블이 없는 모든 기능 플래그를 로드합니다.

중요합니다

Azure App Configuration에서 로드된 기능 플래그를 효과적으로 사용하고 관리하려면 패키지를 설치하고 사용합니다 @microsoft/feature-management . 이 라이브러리는 애플리케이션에서 기능 동작을 제어하는 구조화된 방법을 제공합니다.

기능 관리

기능 관리 라이브러리는 기능 플래그를 기반으로 애플리케이션 기능을 개발하고 노출하는 방법을 제공합니다. 기능 관리 라이브러리는 구성 공급자 라이브러리와 함께 작동하도록 설계되었습니다. 구성 공급자는 선택한 모든 기능 플래그를 섹션 목록 아래 feature_flags 의 구성에 로드합니다 feature_management . 기능 관리 라이브러리는 애플리케이션에 대해 로드된 기능 플래그를 사용하고 관리합니다.

다음 예제에서는 기능 플래그의 @microsoft/feature-management 상태에 따라 Express 애플리케이션에서 API 접근성을 동적으로 제어하도록 라이브러리를 구성 공급자와 통합하는 Beta 방법을 보여 줍니다.

// Load feature flags from Azure App Configuration
import { load } from "@azure/app-configuration-provider";
const appConfig = await load(endpoint, credential, {
    featureFlagOptions: {
        enabled: true, // enable loading feature flags
        refresh: {
            enabled: true // enable refreshing feature flags
        }
    }
});

import { ConfigurationMapFeatureFlagProvider, FeatureManager } from "@microsoft/feature-management";
// Create a feature flag provider which uses the configuration provider as feature flag source
const ffProvider = new ConfigurationMapFeatureFlagProvider(appConfig);
// Create a feature manager which will evaluate the feature flag
const fm = new FeatureManager(ffProvider);

import express from "express";
const server = express();

// Use a middleware to achieve request-driven configuration refresh
server.use((req, res, next) => {
    // this call is not blocking, the configuration will be updated asynchronously
    appConfig.refresh();
    next();
});

server.get("/Beta", async (req, res) => {
    if (await featureManager.isEnabled("Beta")) {
        res.send("Welcome to the Beta page!");
    } else {
        res.status(404).send("Page not found");
    }
});

JavaScript 기능 관리 라이브러리를 사용하는 방법에 대한 자세한 내용은 기능 플래그 빠른 시작을 참조하세요.

Key Vault 참조

Azure 앱 Configuration은 Azure Key Vault에 저장된 비밀 참조를 지원합니다. App Configuration에서 Key Vault에 저장된 비밀에 매핑되는 키를 만들 수 있습니다. 비밀은 Key Vault에 안전하게 저장되지만 로드된 다른 구성처럼 액세스할 수 있습니다.

구성 공급자 라이브러리는 App Configuration에 저장된 다른 키와 마찬가지로 Key Vault 참조를 검색합니다. 클라이언트는 키를 Key Vault 참조로 인식하므로 고유한 콘텐츠 형식을 가지며 클라이언트는 Key Vault에 연결하여 애플리케이션에 대한 값을 검색합니다. 구성 공급자가 Azure Key Vault에 연결할 수 있도록 적절한 자격 증명으로 속성을 구성 AzureAppConfigurationOptions.KeyVaultOptions 해야 합니다.

const credential = new DefaultAzureCredential();
const appConfig = await load(endpoint, credential, {
    keyVaultOptions: {
        credential: credential
    }
});

에 직접 인스턴스를 SecretClient제공할 KeyVaultOptions 수도 있습니다. 이러한 방식으로 만드는 SecretClient동안 옵션을 사용자 지정할 수 있습니다.

import { SecretClient } from "@azure/keyvault-secrets";

const credential = new DefaultAzureCredential();
const secretClient = new SecretClient(keyVaultUrl, credential, {
    serviceVersion: "7.0",
});
const appConfig = await load(endpoint, credential, {
    keyVaultOptions: {
        secretClients: [ secretClient ]
    }
});

Key Vault가 연결되지 않은 비밀을 로컬로 확인하도록 속성을 설정할 secretResolver 수도 있습니다.

const resolveSecret = (url) => "From Secret Resolver";
const appConfig = await load(endpoint, credential, {
    keyVaultOptions: {
        secretResolver: resolveSecret
    }
});

또한 등록되지 않은 clientOptions가 있는 Azure Key Vault에 연결하는 데 사용되는 SecretClientOptions을 구성하기 위해 SecretClient 속성을 설정할 수도 있습니다.

const credential = new DefaultAzureCredential();
const appConfig = await load(endpoint, credential, {
    keyVaultOptions: {
        credential: credential,
        clientOptions: { // configure a custom SecretClientOptions
            retryOptions: { 
                maxRetries: 3, 
                maxRetryDelayInMs: 1000 
            }
        }
    }
});

병렬 비밀 해결

Azure Key Vault는 단일 요청에서 여러 비밀을 검색하기 위한 일괄 처리 API를 제공하지 않습니다. 애플리케이션에서 수많은 Key Vault 참조를 로드해야 하는 경우 parallelSecretResolutionEnabledKeyVaultOptions 속성을 사용하여 병렬 비밀 해결을 활성화하면 성능을 향상시킬 수 있습니다. 이렇게 하면 공급자가 순차적으로가 아니라 여러 비밀을 병렬로 가져올 수 있습니다.

const credential = new DefaultAzureCredential();
const appConfig = await load(endpoint, credential, {
    keyVaultOptions: {
        credential: credential,
        parallelSecretResolutionEnabled: true
    }
});

참고 항목

비밀을 병렬로 확인할 때 Azure Key Vault의 서비스 제한이 발생할 수 있습니다. 제한을 효과적으로 처리하려면 에 적절한 재시도 옵션을 구성하여 SecretClient를 구현하세요. 사용자 지정 SecretClient 인스턴스를 등록하거나 clientOptions를 통해 AzureAppConfigurationOptions.keyVaultOptions를 사용하여 구성할 수 있습니다.

스냅샷

스냅샷 은 App Configuration 저장소의 키-값의 명명된 변경할 수 없는 하위 집합입니다. 스냅샷 구성하는 키-값은 키 및 레이블 필터를 사용하여 만드는 동안 선택됩니다. 스냅샷이 만들어지면 포함된 키-값은 변경되지 않은 상태로 유지됩니다.

스냅샷 선택기를 사용하여 스냅샷에서 키-값 또는 기능 플래그를 로드할 수 있습니다.

const appConfig = await load(endpoint, credential, {
    selectors: [
        { snapshotName: "MySnapshot" }, // load key-values from snapshot
        { keyFilter: "test*", labelFilter: "test" }
    ],
    featureFlagOptions: {
        enabled: true,
        selectors: [
            { snapshotName: "MySnapshot" }, // load feature flags from snapshot
            { keyFilter: "*", labelFilter: "test" }
        ]
    }
});

시작 과정 다시 시도

구성 로드는 애플리케이션을 시작하는 동안 중요한 경로 작업입니다. 안정성을 보장하기 위해 Azure App Configuration 공급자는 초기 구성 로드 중에 강력한 재시도 메커니즘을 구현합니다. 이렇게 하면 성공적인 시작을 방해할 수 있는 일시적인 네트워크 문제로부터 애플리케이션을 보호할 수 있습니다.

다음을 통해 이 동작을 사용자 지정할 수 있습니다.AzureAppConfigurationOptions.startupOptions

const appConfig = await load(endpoint, credential, { 
    startupOptions: { 
        timeoutInMs: 300_000
    }
});

지역에서 복제

지역에서 복제를 사용하는 방법에 대한 자세한 내용은 지역 복제 사용으로 이동하세요.

다음 단계

JavaScript 구성 공급자를 사용하는 방법을 알아보려면 다음 자습서를 계속 진행합니다.

JavaScript 기능 관리 라이브러리를 사용하는 방법을 알아보려면 다음 설명서를 계속 진행하세요.