본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

How-To: 저장소에서 구성 관리하기

원문 보기 위키 갱신

애플리케이션 구성을 가져오고 변경 사항을 구독하는 방법 알아보기 이 예제는 Redis 구성 저장소 컴포넌트를 사용해 구성 항목을 검색하는 방법을 보여줘요.

Note

아직 안 해봤다면, 구성 API 사용법을 빠르게 익힐 수 있는 configuration quickstart를 먼저 시도해 보세요.

구성 초기화 엔드포인트 비활성화

애플리케이션이 구성 빌딩 블록을 사용하지 않는다면, 초기화 중 /dapr/config 엔드포인트로 자동으로 이루어지는 HTTP 호출을 비활성화해 로그 잡음을 줄일 수 있어요. dapr run과 함께 --disable-init-endpoints config 플래그를 쓰거나, Kubernetes에서는 dapr.io/disable-init-endpoints: "config" 어노테이션을 사용해요. 초기화 엔드포인트 비활성화에 대해 자세히 알아보세요.

출처: Dapr 문서

본문

저장소에 구성 항목 만들기

지원되는 구성 저장소에 구성 항목을 만들어요. 원하는 키를 쓰는 간단한 키-값 항목이면 돼요. 앞서 언급했듯이 이 예제는 Redis 구성 저장소 컴포넌트를 사용해요.

Docker로 Redis 실행

docker run --name my-redis -p 6379:6379 -d redis:6

항목 저장하기

Redis CLI를 사용해 Redis 인스턴스에 연결해요:

redis-cli -p 6379

구성 항목을 저장해요:

MSET orderId1 "101||1" orderId2 "102||1"

Dapr 구성 저장소 구성하기

다음 컴포넌트 파일을 머신의 기본 components 폴더에 저장해요. 이것을 Dapr 컴포넌트 YAML로 사용하면 돼요:

  • Kubernetes이면 kubectl을 사용해요.
  • Dapr CLI로 실행할 때.

Note

Redis 구성 컴포넌트는 Redis statestore.yaml 컴포넌트와 메타데이터가 동일하므로, 이미 Redis statestore.yaml이 있다면 Redis 상태 저장소 컴포넌트 유형을 복사/변경하기만 하면 돼요.

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: configstore
spec:
  type: configuration.redis
  metadata:
  - name: redisHost
    value: localhost:6379
  - name: redisPassword
    value: <PASSWORD>

구성 항목 검색하기

구성 항목 가져오기

다음 예제는 Dapr 구성 API를 사용해 저장된 구성 항목을 가져오는 방법을 보여줘요.

  • .NET
  • Java
  • Python
  • Go
  • JavaScript
  • HTTP API (BASH)
  • HTTP API (PowerShell)
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapr.Client;

const string CONFIG_STORE_NAME = "configstore";

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDaprClient();
var app = builder.Build();

using var client = app.Services.GetRequiredServices<DaprClient>();

var configuration = await client.GetConfiguration(CONFIG_STORE_NAME, [ "orderId1", "orderId2" ]);
Console.WriteLine($"Got key=\n{configuration[0].Key} -> {configuration[0].Value}\n{configuration[1].Key} -> {configuration[1].Value}");
//dependencies
import io.dapr.client.DaprClientBuilder;
import io.dapr.client.DaprClient;
import io.dapr.client.domain.ConfigurationItem;
import io.dapr.client.domain.GetConfigurationRequest;
import io.dapr.client.domain.SubscribeConfigurationRequest;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

//code
private static final String CONFIG_STORE_NAME = "configstore";

public static void main(String[] args) throws Exception {
    try (DaprClient client = (new DaprClientBuilder()).build()) {
        List<String> keys = new ArrayList<>();
        keys.add("orderId1");
        keys.add("orderId2");
        GetConfigurationRequest req = new GetConfigurationRequest(CONFIG_STORE_NAME, keys);
        try {
            Mono<List<ConfigurationItem>> items = client.getConfiguration(req);
            items.block().forEach(ConfigurationClient::print);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}
#dependencies
from dapr.clients import DaprClient
#code
with DaprClient() as d:
    CONFIG_STORE_NAME = 'configstore'
    keys = ['orderId1', 'orderId2']
    #Startup time for dapr
    d.wait(20)
    configuration = d.get_configuration(store_name=CONFIG_STORE_NAME, keys=[keys], config_metadata={})
    print(f"Got key={configuration.items[0].key} value={configuration.items[0].value} version={configuration.items[0].version}")
package main

import (
	"context"
	"fmt"

	dapr "github.com/dapr/go-sdk/client"
)

func main() {
	ctx := context.Background()
	client, err := dapr.NewClient()
	if err != nil {
		panic(err)
	}
	items, err := client.GetConfigurationItems(ctx, "configstore", ["orderId1","orderId2"])
	if err != nil {
		panic(err)
	}
	for key, item := range items {
		fmt.Printf("get config: key = %s value = %s version = %s",key,(*item).Value, (*item).Version)
	}
}
import { CommunicationProtocolEnum, DaprClient } from "@dapr/dapr";

// JS SDK does not support Configuration API over HTTP protocol yet
const protocol = CommunicationProtocolEnum.GRPC;
const host = process.env.DAPR_HOST ?? "localhost";
const port = process.env.DAPR_GRPC_PORT ?? 3500;

const DAPR_CONFIGURATION_STORE = "configstore";
const CONFIGURATION_ITEMS = ["orderId1", "orderId2"];

async function main() {
    const client = new DaprClient(host, port, protocol);
    // Get config items from the config store
    try {
        const config = await client.configuration.get(DAPR_CONFIGURATION_STORE, CONFIGURATION_ITEMS);
        Object.keys(config.items).forEach((key) => {
            console.log("Configuration for " + key + ":", JSON.stringify(config.items[key]));
        });
    } catch (error) {
        console.log("Could not get config item, err:" + error);
        process.exit(1);
    }
}

main().catch((e) => console.error(e));

Dapr 사이드카를 실행해요:

dapr run --app-id orderprocessing --dapr-http-port 3601

별도의 터미널에서 아까 저장한 구성 항목을 가져와요:

curl http://localhost:3601/v1.0/configuration/configstore?key=orderId1

Dapr 사이드카를 실행해요:

dapr run --app-id orderprocessing --dapr-http-port 3601

별도의 터미널에서 아까 저장한 구성 항목을 가져와요:

Invoke-RestMethod -Uri 'http://localhost:3601/v1.0/configuration/configstore?key=orderId1'

구성 항목 업데이트 구독하기

아래 코드 예시는 SDK를 사용해 configstore 저장소 컴포넌트의 [orderId1, orderId2] 키를 구독하는 방법을 보여줘요.

  • .NET
  • ASP.NET
  • Java
  • Python
  • Go
  • JavaScript
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapr.Client;
using System.Text.Json;

const string DAPR_CONFIGURATION_STORE = "configstore";
var CONFIGURATION_ITEMS = new List<string> { "orderId1", "orderId2" };

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDaprClient();
var app = builder.Build();

var client = app.Services.GetRequiredService<DaprClient>();

// Subscribe for configuration changes
var subscribe = await client.SubscribeConfiguration(DAPR_CONFIGURATION_STORE, CONFIGURATION_ITEMS);

// Print configuration changes
await foreach (var items in subscribe.Source)
{
    // First invocation when app subscribes to config changes only returns subscription id
    if (items.Keys.Count == 0)
    {
        Console.WriteLine("App subscribed to config changes with subscription id: " + subscribe.Id);
        subscriptionId = subscribe.Id;
        continue;
    }
    var cfg = JsonSerializer.Serialize(items);
    Console.WriteLine("Configuration update " + cfg);
}

위 코드가 있는 디렉터리로 이동한 후, 다음 명령을 실행해 Dapr 사이드카와 구독자 애플리케이션을 함께 실행해요:

dapr run --app-id orderprocessing -- dotnet run
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Dapr.Client;
using Dapr.Extensions.Configuration;
using System.Collections.Generic;
using System.Threading;

Console.WriteLine("Starting application.");
var builder = WebApplication.CreateBuilder(args);

// Unlike most other situations, we build a `DaprClient` here using its factory because we cannot rely on `IConfiguration`
// or other injected services to configure it because we haven't yet built the DI container.
var client = new DaprClientBuilder().Build();

// In a real-world application, you'd also add the following line to register the `DaprClient` with the DI container so
// it can be injected into other services. In this demonstration, it's not necessary as we're not injecting it anywhere.
// builder.Services.AddDaprClient();

// Get the initial value and continue to watch it for changes
builder.Configuration.AddDaprConfigurationStore("configstore", new List<string>() { "orderId1","orderId2" }, client, TimeSpan.FromSeconds(20));
builder.Configuration.AddStreamingDaprConfigurationStore("configstore", new List<string>() { "orderId1","orderId2" }, client, TimeSpan.FromSeconds(20));

await builder.Build().RunAsync();
Console.WriteLine("Closing application.");

위 코드가 있는 디렉터리로 이동한 후, 다음 명령을 실행해 Dapr 사이드카와 구독자 애플리케이션을 함께 실행해요:

dapr run --app-id orderprocessing -- dotnet run
import io.dapr.client.DaprClientBuilder;
import io.dapr.client.DaprClient;
import io.dapr.client.domain.ConfigurationItem;
import io.dapr.client.domain.GetConfigurationRequest;
import io.dapr.client.domain.SubscribeConfigurationRequest;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

//code
private static final String CONFIG_STORE_NAME = "configstore";
private static String subscriptionId = null;

public static void main(String[] args) throws Exception {
    try (DaprClient client = (new DaprClientBuilder()).build()) {
        // Subscribe for config changes
        List<String> keys = new ArrayList<>();
        keys.add("orderId1");
        keys.add("orderId2");
        Flux<SubscribeConfigurationResponse> subscription = client.subscribeConfiguration(DAPR_CONFIGURATON_STORE,keys);

        // Read config changes for 20 seconds
        subscription.subscribe((response) -> {
            // First ever response contains the subscription id
            if (response.getItems() == null || response.getItems().isEmpty()) {
                subscriptionId = response.getSubscriptionId();
                System.out.println("App subscribed to config changes with subscription id: " + subscriptionId);
            } else {
                response.getItems().forEach((k, v) -> {
                    System.out.println("Configuration update for " + k + ": {'value':'" + v.getValue() + "'}");
                });
            }
        });
        Thread.sleep(20000);
    }
}

위 코드가 있는 디렉터리로 이동한 후, 다음 명령을 실행해 Dapr 사이드카와 구독자 애플리케이션을 함께 실행해요:

dapr run --app-id orderprocessing -- -- mvn spring-boot:run
#dependencies
from dapr.clients import DaprClient
#code

def handler(id: str, resp: ConfigurationResponse):
    for key in resp.items:
        print(f"Subscribed item received key={key} value={resp.items[key].value} "
              f"version={resp.items[key].version} "
              f"metadata={resp.items[key].metadata}", flush=True)

def executeConfiguration():
    with DaprClient() as d:
        storeName = 'configurationstore'
        keys = ['orderId1', 'orderId2']
        id = d.subscribe_configuration(store_name=storeName, keys=keys,
                                       handler=handler, config_metadata={})
        print("Subscription ID is", id, flush=True)
        sleep(20)

executeConfiguration()

위 코드가 있는 디렉터리로 이동한 후, 다음 명령을 실행해 Dapr 사이드카와 구독자 애플리케이션을 함께 실행해요:

dapr run --app-id orderprocessing -- python3 OrderProcessingService.py
package main

import (
	"context"
	"fmt"
	"time"

	dapr "github.com/dapr/go-sdk/client"
)

func main() {
	ctx := context.Background()
	client, err := dapr.NewClient()
	if err != nil {
		panic(err)
	}
	subscribeID, err := client.SubscribeConfigurationItems(ctx, "configstore", []string{"orderId1", "orderId2"}, func(id string, items map[string]*dapr.ConfigurationItem) {
		for k, v := range items {
			fmt.Printf("get updated config key = %s, value = %s version = %s \n", k, v.Value, v.Version)
		}
	})
	if err != nil {
		panic(err)
	}
	time.Sleep(20*time.Second)
}

위 코드가 있는 디렉터리로 이동한 후, 다음 명령을 실행해 Dapr 사이드카와 구독자 애플리케이션을 함께 실행해요:

dapr run --app-id orderprocessing -- go run main.go
import { CommunicationProtocolEnum, DaprClient } from "@dapr/dapr";

// JS SDK does not support Configuration API over HTTP protocol yet
const protocol = CommunicationProtocolEnum.GRPC;
const host = process.env.DAPR_HOST ?? "localhost";
const port = process.env.DAPR_GRPC_PORT ?? 3500;

const DAPR_CONFIGURATION_STORE = "configstore";
const CONFIGURATION_ITEMS = ["orderId1", "orderId2"];

async function main() {
    const client = new DaprClient(host, port, protocol);
    // Subscribe to config updates
    try {
        const stream = await client.configuration.subscribeWithKeys(
            DAPR_CONFIGURATION_STORE,
            CONFIGURATION_ITEMS,
            (config) => {
                console.log("Configuration update", JSON.stringify(config.items));
            }
        );
        // Unsubscribe to config updates and exit app after 20 seconds
        setTimeout(() => {
            stream.stop();
            console.log("App unsubscribed to config changes");
            process.exit(0);
        }, 20000);
    } catch (error) {
        console.log("Error subscribing to config updates, err:" + error);
        process.exit(1);
    }
}
main().catch((e) => console.error(e));

위 코드가 있는 디렉터리로 이동한 후, 다음 명령을 실행해 Dapr 사이드카와 구독자 애플리케이션을 함께 실행해요:

dapr run --app-id orderprocessing --app-protocol grpc --dapr-grpc-port 3500 -- node index.js

구성 항목 업데이트 구독 취소하기

구성 항목을 구독한 뒤에는 구독한 모든 키에 대한 업데이트를 받게 돼요. 업데이트 수신을 중단하려면 unsubscribe API를 명시적으로 호출해야 해요. 다음은 unsubscribe API를 사용해 구성 업데이트 구독을 취소하는 방법을 보여주는 코드 예시예요.

  • .NET
  • Java
  • Python
  • Go
  • JavaScript
  • HTTP API (BASH)
  • HTTP API (PowerShell)
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapr.Client;

var builder = WebApplication.CreateBuilder();
builder.Services.AddDaprClient();
var app = builder.Build();

const string DAPR_CONFIGURATION_STORE = "configstore";
const string SubscriptionId = "abc123"; //Replace with the subscription identifier to unsubscribe from
var client = app.Services.GetRequiredService<DaprClient>();

await client.UnsubscribeConfiguration(DAPR_CONFIGURATION_STORE, SubscriptionId);
Console.WriteLine("App unsubscribed from config changes");
import io.dapr.client.DaprClientBuilder;
import io.dapr.client.DaprClient;
import io.dapr.client.domain.ConfigurationItem;
import io.dapr.client.domain.GetConfigurationRequest;
import io.dapr.client.domain.SubscribeConfigurationRequest;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

//code
private static final String CONFIG_STORE_NAME = "configstore";
private static String subscriptionId = null;

public static void main(String[] args) throws Exception {
    try (DaprClient client = (new DaprClientBuilder()).build()) {
        // Unsubscribe from config changes
        UnsubscribeConfigurationResponse unsubscribe = client
                .unsubscribeConfiguration(subscriptionId, DAPR_CONFIGURATON_STORE).block();
        if (unsubscribe.getIsUnsubscribed()) {
            System.out.println("App unsubscribed to config changes");
        } else {
            System.out.println("Error unsubscribing to config updates, err:" + unsubscribe.getMessage());
        }
    } catch (Exception e) {
        System.out.println("Error unsubscribing to config updates," + e.getMessage());
        System.exit(1);
    }
}
import asyncio
import time
import logging
from dapr.clients import DaprClient
subscriptionID = ""

with DaprClient() as d:
    isSuccess = d.unsubscribe_configuration(store_name='configstore', id=subscriptionID)
    print(f"Unsubscribed successfully? {isSuccess}", flush=True)
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"time"

	dapr "github.com/dapr/go-sdk/client"
)

var DAPR_CONFIGURATION_STORE = "configstore"
var subscriptionID = ""

func main() {
	client, err := dapr.NewClient()
	if err != nil {
		log.Panic(err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := client.UnsubscribeConfigurationItems(ctx, DAPR_CONFIGURATION_STORE , subscriptionID); err != nil {
		panic(err)
	}
}
import { CommunicationProtocolEnum, DaprClient } from "@dapr/dapr";

// JS SDK does not support Configuration API over HTTP protocol yet
const protocol = CommunicationProtocolEnum.GRPC;
const host = process.env.DAPR_HOST ?? "localhost";
const port = process.env.DAPR_GRPC_PORT ?? 3500;

const DAPR_CONFIGURATION_STORE = "configstore";
const CONFIGURATION_ITEMS = ["orderId1", "orderId2"];

async function main() {
    const client = new DaprClient(host, port, protocol);

    try {
        const stream = await client.configuration.subscribeWithKeys(
            DAPR_CONFIGURATION_STORE,
            CONFIGURATION_ITEMS,
            (config) => {
                console.log("Configuration update", JSON.stringify(config.items));
            }
        );
        setTimeout(() => {
            // Unsubscribe to config updates
            stream.stop();
            console.log("App unsubscribed to config changes");
            process.exit(0);
        }, 20000);
    } catch (error) {
        console.log("Error subscribing to config updates, err:" + error);
        process.exit(1);
    }
}

main().catch((e) => console.error(e));
curl 'http://localhost:<DAPR_HTTP_PORT>/v1.0/configuration/configstore/<subscription-id>/unsubscribe'
Invoke-RestMethod -Uri 'http://localhost:<DAPR_HTTP_PORT>/v1.0/configuration/configstore/<subscription-id>/unsubscribe'

다음 단계

  • 구성 API 개요 읽기

더 알아보기 (Learn more)