다음을 통해 공유


JavaScript용 Azure App Configuration 클라이언트 라이브러리 - 버전 1.10.0

Azure App Configuration 개발자가 애플리케이션 및 기능 설정을 간단하고 안전하게 중앙 집중화하는 데 도움이 되는 관리형 서비스입니다.

키 링크:

올바른 패키지 선택

@azure/app-configuration(이 라이브러리)을 사용하여 다음을 수행합니다.

  • Azure App Configuration에서 구성 설정 및 스냅숏 관리
  • 정상적인 구성 소비 영역 밖에서 작동하는 세분화된 읽기 수행

대부분의 애플리케이션은 이 하위 수준 클라이언트 라이브러리를 기반으로 하며 런타임에 구성을 사용하는 데 권장되는 방법인 @azure/app-configuration-provider 라이브러리로 시작해야 합니다. 다음과 같이 덧붙입니다.

  • 구성을 키/값 맵 또는 구조화된 JSON 객체로 사용하는 유연한 액세스 패턴
  • 선언적으로 앱 구성을 작성하는 쿼리 메커니즘
  • 런타임 중 구성 새로 고침
  • 캐싱, 복제본 검색, 장애 조치 및 로드 밸런싱을 통한 높은 안정성
  • 키 자격 증명 모음 참조 확인 및 자동 새로 고침
  • @microsoft/기능 관리 라이브러리에 대한 기능 플래그 통합

자세한 내용은 구성 공급자 개요로 이동하세요.

시작

패키지 설치

npm install @azure/app-configuration

메모:구성 값만 읽어야 하는 애플리케이션의 경우 대신 @azure/app-configuration-provider 라이브러리를 사용하는 것이 좋습니다.

현재 지원되는 환경

자세한 내용은 지원 정책 참조하세요.

필수 구성 요소

App Configuration 리소스 만들기

Azure Portal 또는 Azure CLI 사용하여 Azure App Configuration 리소스를 만들 수 있습니다.

예제(Azure CLI):

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

클라이언트 인증

AppConfigurationClient는 서비스 주체 사용하거나 연결 문자열사용하여 인증할 수 있습니다.

서비스 주체를 사용하여 인증

서비스 주체를 통한 인증은 다음을 통해 수행됩니다.

  • @azure/identity 패키지를 사용하여 자격 증명 만들기
  • AppConfiguration 리소스에 적절한 RBAC 규칙 설정 App Configuration 역할에 대한 자세한 내용은여기에서 찾을 수 있습니다.

DefaultAzureCredential 사용

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

대한 자세한 내용은 여기에서 찾을 수 있습니다.

소버린 클라우드

소버린 클라우드의 리소스로 인증하려면 생성자 옵션에서 audience 를 설정 AppConfigurationClient 해야 합니다.

import { AppConfigurationClient, KnownAppConfigAudience } from "@azure/app-configuration";
import { DefaultAzureCredential } from "@azure/identity";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.azure.cn";
// Create an AppConfigurationClient that will authenticate through AAD in the China cloud
const client = new AppConfigurationClient(endpoint, new DefaultAzureCredential(), {
  audience: KnownAppConfigAudience.AzureChina,
});

참고: 속성이 정의되지 않은 경우 audience SDK는 기본적으로 Azure 퍼블릭 클라우드로 설정됩니다.

연결 문자열을 사용하여 인증

App Configuration 리소스에 대한 기본 연결 문자열 얻으려면 다음 Azure CLI 명령을 사용할 수 있습니다.

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

이제 코드에서 Azure CLI에서 얻은 연결 문자열을 사용하여 App Configuration 클라이언트를 만들 수 있습니다.

import { AppConfigurationClient } from "@azure/app-configuration";

const connectionString = "Endpoint=https://example.azconfig.io;XXX=YYYY;YYY=ZZZZ";
const client = new AppConfigurationClient(connectionString);

주요 개념

AppConfigurationClient 포털의 App Configuration에서 몇 가지 용어를 변경합니다.

  • 키/값 쌍은 ConfigurationSetting 개체로 표시됩니다.
  • 설정 잠금 및 잠금 해제는 isReadOnly사용하여 전환할 수 있는 setReadOnly 필드에 표시됩니다.
  • 스냅샷은 ConfigurationSnapshot 개체로 표시됩니다.

클라이언트는 간단한 디자인 방법론을 따릅니다. ConfigurationSettingConfigurationSettingParam 사용하거나 ConfigurationSettingId모든 메서드에 전달할 수 있습니다.

즉, 이 패턴은 다음과 같이 작동합니다.

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

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);

또는, 예를 들어 설정을 다시 가져오는 경우:

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

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

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

2022-11-01-preview API 버전은 구성 스냅샷을 지원합니다. 변경 불가능한 구성 저장소의 지정 시간 복사본입니다. 스냅샷에 포함된 키-값 쌍을 결정하는 필터를 사용하여 스냅샷을 만들 수 있으며, 구성 저장소의 변경할 수 없는 구성 보기를 만들 수 있습니다. 이 기능을 사용하면 애플리케이션이 일관된 구성 보기를 유지할 수 있으므로 업데이트가 수행된 대로 읽기 때문에 개별 설정에 대한 버전 불일치가 없도록 할 수 있습니다. 예를 들어 이 기능을 사용하여 App Configuration 내에서 "릴리스 구성 스냅샷"을 만들 수 있습니다. 아래 예제에서 스냅샷 섹션 만들고 가져오는 참조하세요.

예제

메모: 애플리케이션이 구성 값만 검색해야 하고 구성 설정에 대해 생성, 업데이트 또는 삭제 작업을 수행할 필요가 없는 경우 대신 @azure/app-configuration-provider 라이브러리를 사용하는 것이 좋습니다. 공급자 라이브러리는 런타임 시 구성 데이터 및 추가 기능을 로드하기 위한 간소화된 환경을 제공합니다. Microsoft Learn의 Azure App Configuration 설명서에서 많은 코드 샘플을 찾을 수 있습니다.

설정 만들기 및 가져오기

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

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.
  // https://learn.microsoft.com/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);

스냅샷 만들기

beginCreateSnapshot 스냅샷 생성을 폴링할 수 있는 폴러를 제공합니다.

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

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();

beginCreateSnapshotAndWait 사용하여 폴링이 완료된 직후 생성 결과를 가져올 수도 있습니다.

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

const key = "testkey";
const value = "testvalue";
const label = "optional-label";

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

스냅샷 가져오기

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

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

스냅샷의 ConfigurationSetting 나열

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

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

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

서비스의 모든 스냅샷 나열

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

const snapshots = await client.listSnapshots();

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

스냅샷 복구 및 보관

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

// 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설정합니다. 또는 setLogLevel@azure/logger 호출하여 런타임에 로깅을 사용하도록 설정할 수 있습니다.

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

로그를 사용하도록 설정하는 방법에 대한 자세한 지침은 @azure/로거 패키지 문서확인할 수 있습니다.

React 네이티브 지원

React Native는 이 SDK 라이브러리에서 사용하는 일부 JavaScript API를 지원하지 않으므로 폴리필을 제공해야 합니다. 자세한 내용은 Expo React Native 샘플을 참조하세요.

다음 단계

다음 샘플에서는 App Configuration과 상호 작용할 수 있는 다양한 방법을 보여줍니다.

  • helloworld.ts - 구성 값을 가져오기, 설정 및 삭제합니다.
  • helloworldWithLabels.ts - 레이블을 사용하여 베타 및 프로덕션과 같은 시나리오의 설정에 차원을 더 추가합니다.
  • optimisticConcurrencyViaEtag.ts - 실수로 덮어쓰지 않도록 etag를 사용하여 값을 설정합니다.
  • setReadOnlySample.ts - 수정을 방지하기 위해 설정을 읽기 전용으로 표시합니다.
  • getSettingOnlyIfChanged.ts - 마지막으로 설정한 시점부터 변경된 경우에만 설정을 가져옵니다.
  • listRevisions.ts - 키의 수정 버전을 나열하여 이전 값과 설정 시기를 볼 수 있도록 합니다.
  • secretReference.ts - SecretReference는 KeyVault 비밀로 참조하는 구성 설정을 나타냅니다.
  • snapshot.ts - 만들기, 구성 설정 나열 및 스냅샷 보관
  • featureFlag.ts - 기능 플래그는 값에 대한 특정 JSON 스키마를 따르는 설정입니다.

자세한 예제는 GitHub의 샘플 폴더에서 찾을 수 있습니다.

기여

이 라이브러리에 기여하려면 기여 가이드 읽어 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.

이 모듈의 테스트는 라이브 및 단위 테스트가 혼합되어 있으므로 Azure App Configuration 인스턴스가 있어야 합니다. 테스트를 실행하려면 다음을 실행해야 합니다.

  1. pnpm install
  2. pnpm build --filter @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;

자세한 내용은 테스트 폴더를 참조하세요.