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

How-To: 상태 저장하고 가져오기

원문 보기 위키 갱신

키-값 쌍으로 상태를 영속화하는 방법을 알아볼게요.

상태 관리는 새 애플리케이션이든, 레거시, 모놀리스, 마이크로서비스 애플리케이션이든 가장 흔한 요구 중 하나예요. 다양한 데이터베이스 라이브러리를 다루고 테스트하며, 재시도와 장애를 처리하는 일은 어렵고 시간이 많이 걸릴 수 있어요.

이 가이드에서는 키/값 상태 API의 기초를 배워 애플리케이션이 상태를 저장(save), 가져오기(get), 삭제(delete)할 수 있게 해요. 아래 코드 예시는 Dapr 사이드카가 있는 주문 처리 서비스로 주문을 처리하는 애플리케이션을 개략적으로 보여줘요. 주문 처리 서비스는 Dapr을 사용해 상태를 Redis 상태 저장소에 저장해요.

출처: Dapr 문서

본문

상태 저장소 설정하기

상태 저장소 컴포넌트는 Dapr이 데이터베이스와 통신할 때 사용하는 리소스를 나타내요. 이 가이드에서는 Redis 상태 저장소를 사용하지만, 지원 목록에 있는 어떤 상태 저장소든 동작해요.

  • Self-Hosted (CLI)
  • Kubernetes

셀프 호스트 모드에서 dapr init을 실행하면 Dapr이 기본 Redis statestore.yaml을 만들고 로컬 머신에 Redis 상태 저장소를 실행해요. 위치는:

  • Windows의 경우 %UserProfile%\.dapr\components\statestore.yaml
  • Linux/MacOS의 경우 ~/.dapr/components/statestore.yaml

statestore.yaml 컴포넌트를 사용하면 애플리케이션 코드 변경 없이 기본 컴포넌트를 쉽게 교체할 수 있어요.

Kubernetes 클러스터에 배포하려면 아래 YAML의 상태 저장소 컴포넌트 metadata 연결 세부 정보를 채우고, statestore.yaml로 저장한 뒤 kubectl apply -f statestore.yaml을 실행해요.

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: statestore
spec:
  type: state.redis
  version: v1
  metadata:
  - name: redisHost
    value: localhost:6379
  - name: redisPassword
    value: ""

Kubernetes에서 다른 상태 저장소를 설정하는 방법을 확인해 보세요.

중요

app-id를 설정하세요. 상태 키가 이 값으로 접두사가 붙기 때문이에요. app-id를 설정하지 않으면 런타임에 자동으로 생성돼요. 다음에 명령을 실행하면 새 app-id가 생성되고, 이전에 저장한 상태에 더 이상 접근할 수 없게 돼요.

팁

로컬에서 실행할 때는 Dapr Dev Dashboard를 사용해 이 페이지의 예시 결과를 확인할 수 있어요. 대시보드에서는 상태 저장소의 레코드(app-id 키 접두사 포함)를 탐색하고, base64 인코딩된 값을 디코딩하며, 코드를 작성하지 않고도 레코드를 추가하거나 삭제할 수 있어요.

단일 상태 저장 및 가져오기

다음 예시는 Dapr 상태 관리 API로 단일 키/값 쌍을 저장하고 가져오는 방법을 보여줘요.

  • .NET
  • Java
  • Python
  • Go
  • JavaScript
  • HTTP API (Bash)
  • HTTP API (PowerShell)

using System.Text;
using System.Threading.Tasks;
using Dapr.Client;

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

var random = new Random();
//Resolve the DaprClient from its dependency injection registration
using var client = app.Services.GetRequiredService<DaprClient>();

while(true)
{
    await Task.Delay(TimeSpan.FromSeconds(5));
    var orderId = random.Next(1,1000);
    //Using Dapr SDK to save and get state
    await client.SaveStateAsync(DAPR_STORE_NAME, "order_1", orderId.ToString());
    await client.SaveStateAsync(DAPR_STORE_NAME, "order_2", orderId.ToString());
    var result = await client.GetStateAsync<string>(DAPR_STORE_NAME, "order_1");
    Console.WriteLine($"Result after get: {result}");
}

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 dotnet run
//dependencies
import io.dapr.client.DaprClient;
import io.dapr.client.DaprClientBuilder;
import io.dapr.client.domain.State;
import io.dapr.client.domain.TransactionalStateOperation;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import java.util.Random;
import java.util.concurrent.TimeUnit;

//code
@SpringBootApplication
public class OrderProcessingServiceApplication {

    private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);

    private static final String STATE_STORE_NAME = "statestore";

    public static void main(String[] args) throws InterruptedException{
        while(true) {
            TimeUnit.MILLISECONDS.sleep(5000);
            Random random = new Random();
            int orderId = random.nextInt(1000-1) + 1;
            DaprClient client = new DaprClientBuilder().build();
            //Using Dapr SDK to save and get state
            client.saveState(STATE_STORE_NAME, "order_1", Integer.toString(orderId)).block();
            client.saveState(STATE_STORE_NAME, "order_2", Integer.toString(orderId)).block();
            Mono<State<String>> result = client.getState(STATE_STORE_NAME, "order_1", String.class);
            log.info("Result after get" + result);
        }
    }

}

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 mvn spring-boot:run
#dependencies
import random
from time import sleep
import requests
import logging
from dapr.clients import DaprClient
from dapr.clients.grpc._state import StateItem
from dapr.clients.grpc._request import TransactionalStateOperation, TransactionOperationType

#code
logging.basicConfig(level = logging.INFO)
DAPR_STORE_NAME = "statestore"
while True:
    sleep(random.randrange(50, 5000) / 1000)
    orderId = random.randint(1, 1000)
    with DaprClient() as client:
        #Using Dapr SDK to save and get state
        client.save_state(DAPR_STORE_NAME, "order_1", str(orderId))
        result = client.get_state(DAPR_STORE_NAME, "order_1")
        logging.info('Result after get: ' + result.data.decode('utf-8'))

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 -- python3 OrderProcessingService.py
// dependencies
import (
    "context"
    "log"
    "math/rand"
    "strconv"
    "time"

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

// code
func main() {
    const STATE_STORE_NAME = "statestore"
    rand.Seed(time.Now().UnixMicro())
    for i := 0; i < 10; i++ {
        orderId := rand.Intn(1000-1) + 1
        client, err := dapr.NewClient()
        if err != nil {
            panic(err)
        }
        defer client.Close()
        ctx := context.Background()
        err = client.SaveState(ctx, STATE_STORE_NAME, "order_1", []byte(strconv.Itoa(orderId)), nil)
        if err != nil {
            panic(err)
        }
        result, err := client.GetState(ctx, STATE_STORE_NAME, "order_1", nil)
        if err != nil {
            panic(err)
        }
        log.Println("Result after get:", string(result.Value))
        time.Sleep(2 * time.Second)
    }
}

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 go run OrderProcessingService.go
//dependencies
import { DaprClient, HttpMethod, CommunicationProtocolEnum } from '@dapr/dapr';

//code
const daprHost = "127.0.0.1";
var main = function() {
    for(var i=0;i<10;i++) {
        sleep(5000);
        var orderId = Math.floor(Math.random() * (1000 - 1) + 1);
        start(orderId).catch((e) => {
            console.error(e);
            process.exit(1);
        });
    }
}

async function start(orderId) {
    const client = new DaprClient({
        daprHost,
        daprPort: process.env.DAPR_HTTP_PORT,
        communicationProtocol: CommunicationProtocolEnum.HTTP,
    });
    const STATE_STORE_NAME = "statestore";
    //Using Dapr SDK to save and get state
    await client.state.save(STATE_STORE_NAME, [
        {
            key: "order_1",
            value: orderId.toString()
        },
        {
            key: "order_2",
            value: orderId.toString()
        }
    ]);
    var result = await client.state.get(STATE_STORE_NAME, "order_1");
    console.log("Result after get: " + result);
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

main();

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 npm start

Dapr 사이드카를 시작해요:

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

별도의 터미널에서 statestore에 키/값 쌍을 저장해요:

curl -X POST -H "Content-Type: application/json" -d '[{ "key": "order_1", "value": "250"}]' http://localhost:3601/v1.0/state/statestore

이제 방금 저장한 상태를 가져와요:

curl http://localhost:3601/v1.0/state/statestore/order_1

사이드카를 재시작하고 다시 상태를 가져와서, 상태가 앱과 별개로 영속화되는지 확인해 보세요.

Dapr 사이드카를 시작해요:

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

별도의 터미널에서 statestore에 키/값 쌍을 저장해요:

Invoke-RestMethod -Method Post -ContentType 'application/json' -Body '[{"key": "order_1", "value": "250"}]' -Uri 'http://localhost:3601/v1.0/state/statestore'

이제 방금 저장한 상태를 가져와요:

Invoke-RestMethod -Uri 'http://localhost:3601/v1.0/state/statestore/order_1'

사이드카를 재시작하고 다시 상태를 가져와서, 상태가 앱과 별개로 영속화되는지 확인해 보세요.

상태 삭제

아래는 상태를 삭제하기 위해 Dapr SDK를 활용하는 코드 예시예요.

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

const string DAPR_STORE_NAME = "statestore";

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

//Resolve the DaprClient from the dependency injection registration
using var client = app.Services.GetRequiredService<DaprClient>();

//Use the DaprClient to delete the state
await client.DeleteStateAsync(DAPR_STORE_NAME, "order_1", cancellationToken: cancellationToken);

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 dotnet run
//dependencies
import io.dapr.client.DaprClient;
import io.dapr.client.DaprClientBuilder;
import org.springframework.boot.autoconfigure.SpringBootApplication;

//code
@SpringBootApplication
public class OrderProcessingServiceApplication {
    public static void main(String[] args) throws InterruptedException{
        String STATE_STORE_NAME = "statestore";

        //Using Dapr SDK to delete the state
        DaprClient client = new DaprClientBuilder().build();
        String storedEtag = client.getState(STATE_STORE_NAME, "order_1", String.class).block().getEtag();
        client.deleteState(STATE_STORE_NAME, "order_1", storedEtag, null).block();
    }
}

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 mvn spring-boot:run
#dependencies
from dapr.clients.grpc._request import TransactionalStateOperation, TransactionOperationType

#code
logging.basicConfig(level = logging.INFO)
DAPR_STORE_NAME = "statestore"

#Using Dapr SDK to delete the state
with DaprClient() as client:
    client.delete_state(store_name=DAPR_STORE_NAME, key="order_1")

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 -- python3 OrderProcessingService.py
//dependencies
import (
    "context"
    dapr "github.com/dapr/go-sdk/client"

)

//code
func main() {
    STATE_STORE_NAME := "statestore"
    //Using Dapr SDK to delete the state
    client, err := dapr.NewClient()
    if err != nil {
        panic(err)
    }
    defer client.Close()
    ctx := context.Background()

    if err := client.DeleteState(ctx, STATE_STORE_NAME, "order_1"); err != nil {
        panic(err)
    }
}

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 go run OrderProcessingService.go
//dependencies
import { DaprClient, HttpMethod, CommunicationProtocolEnum } from '@dapr/dapr';

//code
const daprHost = "127.0.0.1";
var main = function() {
    const STATE_STORE_NAME = "statestore";
    //Using Dapr SDK to save and get state
    const client = new DaprClient({
        daprHost,
        daprPort: process.env.DAPR_HTTP_PORT,
        communicationProtocol: CommunicationProtocolEnum.HTTP,
    });

    await client.state.delete(STATE_STORE_NAME, "order_1");
}

main();

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 npm start

위에서 실행 중인 같은 Dapr 인스턴스로 다음을 실행해요.

curl -X DELETE 'http://localhost:3601/v1.0/state/statestore/order_1'

상태를 다시 가져와 보세요. 값이 반환되지 않음을 확인할 수 있어요.

위에서 실행 중인 같은 Dapr 인스턴스로 다음을 실행해요.

Invoke-RestMethod -Method Delete -Uri 'http://localhost:3601/v1.0/state/statestore/order_1'

상태를 다시 가져와 보세요. 값이 반환되지 않음을 확인할 수 있어요.

여러 상태 저장 및 가져오기

아래는 여러 상태를 저장하고 가져오기 위해 Dapr SDK를 활용하는 코드 예시예요.

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

const string DAPR_STORE_NAME = "statestore";

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

//Resolve the DaprClient from the dependency injection registration
using var client = app.Services.GetRequiredService<DaprClient>();

IReadOnlyList<BulkStateItem> multipleStateResult = await client.GetBulkStateAsync(DAPR_STORE_NAME, new List<string> { "order_1", "order_2" }, parallelism: 1);

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 dotnet run

위 예시는 상태에 저장한 값의 직렬화된 형식이 담긴 BulkStateItem을 반환해요. 벌크 응답 항목마다 SDK가 값을 역직렬화하길 원한다면 다음을 대신 사용할 수 있어요.

using Dapr.Client;
using System.Threading.Tasks;

const string DAPR_STORE_NAME = "statestore";

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

//Resolve the DaprClient from the dependency injection registration
using var client = app.Services.GetRequiredService<DaprClient>();

IReadOnlyList<BulkStateItem<Widget>> mulitpleStateResult = await client.GetBulkStateAsync<Widget>(DAPR_STORE_NAME, new List<string> { "widget_1", "widget_2" }, parallelism: 1);

record Widget(string Size, string Color);
//dependencies
import io.dapr.client.DaprClient;
import io.dapr.client.DaprClientBuilder;
import io.dapr.client.domain.State;
import java.util.Arrays;

//code
@SpringBootApplication
public class OrderProcessingServiceApplication {

    private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);

    public static void main(String[] args) throws InterruptedException{
        String STATE_STORE_NAME = "statestore";
        //Using Dapr SDK to retrieve multiple states
        DaprClient client = new DaprClientBuilder().build();
        Mono<List<State<String>>> resultBulk = client.getBulkState(STATE_STORE_NAME,
                Arrays.asList("order_1", "order_2"), String.class);
    }
}

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 mvn spring-boot:run
#dependencies
from dapr.clients import DaprClient
from dapr.clients.grpc._state import StateItem

#code
logging.basicConfig(level = logging.INFO)
DAPR_STORE_NAME = "statestore"
orderId = 100
#Using Dapr SDK to save and retrieve multiple states
with DaprClient() as client:
    client.save_bulk_state(store_name=DAPR_STORE_NAME, states=[StateItem(key="order_2", value=str(orderId))])
    result = client.get_bulk_state(store_name=DAPR_STORE_NAME, keys=["order_1", "order_2"], states_metadata={"metakey": "metavalue"}).items
    logging.info('Result after get bulk: ' + str(result))

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 -- python3 OrderProcessingService.py
// dependencies
import (
    "context"
    "log"
    "math/rand"
    "strconv"
    "time"

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

// code
func main() {
    const STATE_STORE_NAME = "statestore"
    rand.Seed(time.Now().UnixMicro())
    for i := 0; i < 10; i++ {
        orderId := rand.Intn(1000-1) + 1
        client, err := dapr.NewClient()
        if err != nil {
            panic(err)
        }
        defer client.Close()
        ctx := context.Background()
        err = client.SaveState(ctx, STATE_STORE_NAME, "order_1", []byte(strconv.Itoa(orderId)), nil)
        if err != nil {
            panic(err)
        }
        keys := []string{"key1", "key2", "key3"}
        items, err := client.GetBulkState(ctx, STATE_STORE_NAME, keys, nil, 100)
        if err != nil {
            panic(err)
        }
        for _, item := range items {
            log.Println("Item from GetBulkState:", string(item.Value))
        }
    }
}

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 go run OrderProcessingService.go
//dependencies
import { DaprClient, HttpMethod, CommunicationProtocolEnum } from '@dapr/dapr';

//code
const daprHost = "127.0.0.1";
var main = function() {
    const STATE_STORE_NAME = "statestore";
    var orderId = 100;
    //Using Dapr SDK to save and retrieve multiple states
    const client = new DaprClient({
        daprHost,
        daprPort: process.env.DAPR_HTTP_PORT,
        communicationProtocol: CommunicationProtocolEnum.HTTP,
    });

    await client.state.save(STATE_STORE_NAME, [
        {
            key: "order_1",
            value: orderId.toString()
        },
        {
            key: "order_2",
            value: orderId.toString()
        }
    ]);
    result = await client.state.getBulk(STATE_STORE_NAME, ["order_1", "order_2"]);
}

main();

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 npm start

위에서 실행 중인 같은 Dapr 인스턴스로 statestore에 두 개의 키/값 쌍을 저장해요.

curl -X POST -H "Content-Type: application/json" -d '[{ "key": "order_1", "value": "250"}, { "key": "order_2", "value": "550"}]' http://localhost:3601/v1.0/state/statestore

이제 방금 저장한 상태들을 가져와요:

curl -X POST -H "Content-Type: application/json" -d '{"keys":["order_1", "order_2"]}' http://localhost:3601/v1.0/state/statestore/bulk

위에서 실행 중인 같은 Dapr 인스턴스로 statestore에 두 개의 키/값 쌍을 저장해요.

Invoke-RestMethod -Method Post -ContentType 'application/json' -Body '[{ "key": "order_1", "value": "250"}, { "key": "order_2", "value": "550"}]' -Uri 'http://localhost:3601/v1.0/state/statestore'

이제 방금 저장한 상태들을 가져와요:

Invoke-RestMethod -Method Post -ContentType 'application/json' -Body '{"keys":["order_1", "order_2"]}' -Uri 'http://localhost:3601/v1.0/state/statestore/bulk'

상태 트랜잭션 수행하기

참고

상태 트랜잭션은 다중 항목 트랜잭션을 지원하는 상태 저장소가 필요해요. 전체 목록은 지원되는 상태 저장소 페이지를 참고해요.

아래는 상태 트랜잭션을 수행하기 위해 Dapr SDK를 활용하는 코드 예시예요.

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

const string DAPR_STORE_NAME = "statestore";

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

//Resolve the DaprClient from the dependency injection registration
using var client = app.Services.GetRequiredService<DaprClient>();

var random = new Random();

while (true)
{
    await Task.Delay(TimeSpan.FromSeconds(5));
    var orderId = random.Next(1, 1000);
    var requests = new List<StateTransactionRequest>
    {
        new StateTransactionRequest("order_3", JsonSerializer.SerializeToUtf8Bytes(orderId.ToString()), StateOperationType.Upsert),
        new StateTransactionRequest("order_2", null, StateOperationType.Delete)
    };
    var cancellationTokenSource = new CancellationTokenSource();
    var cancellationToken = cancellationTokenSource.Token;

    //Use the DaprClient to perform the state transactions
    await client.ExecuteStateTransactionAsync(DAPR_STORE_NAME, requests, cancellationToken: cancellationToken);
    Console.WriteLine($"Order requested: {orderId}");
    Console.WriteLine($"Result: {result}");
}

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 dotnet run
//dependencies
import io.dapr.client.DaprClient;
import io.dapr.client.DaprClientBuilder;
import io.dapr.client.domain.State;
import io.dapr.client.domain.TransactionalStateOperation;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

//code
@SpringBootApplication
public class OrderProcessingServiceApplication {

    private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);

    private static final String STATE_STORE_NAME = "statestore";

    public static void main(String[] args) throws InterruptedException{
        while(true) {
            TimeUnit.MILLISECONDS.sleep(5000);
            Random random = new Random();
            int orderId = random.nextInt(1000-1) + 1;
            DaprClient client = new DaprClientBuilder().build();
            List<TransactionalStateOperation<?>> operationList = new ArrayList<>();
            operationList.add(new TransactionalStateOperation<>(TransactionalStateOperation.OperationType.UPSERT,
                    new State<>("order_3", Integer.toString(orderId), "")));
            operationList.add(new TransactionalStateOperation<>(TransactionalStateOperation.OperationType.DELETE,
                    new State<>("order_2")));
            //Using Dapr SDK to perform the state transactions
            client.executeStateTransaction(STATE_STORE_NAME, operationList).block();
            log.info("Order requested: " + orderId);
        }
    }

}

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 mvn spring-boot:run
#dependencies
import random
from time import sleep
import requests
import logging
from dapr.clients import DaprClient
from dapr.clients.grpc._state import StateItem
from dapr.clients.grpc._request import TransactionalStateOperation, TransactionOperationType

#code
logging.basicConfig(level = logging.INFO)
DAPR_STORE_NAME = "statestore"
while True:
    sleep(random.randrange(50, 5000) / 1000)
    orderId = random.randint(1, 1000)
    with DaprClient() as client:
        #Using Dapr SDK to perform the state transactions
        client.execute_state_transaction(store_name=DAPR_STORE_NAME, operations=[
            TransactionalStateOperation(
                operation_type=TransactionOperationType.upsert,
                key="order_3",
                data=str(orderId)),
            TransactionalStateOperation(key="order_3", data=str(orderId)),
            TransactionalStateOperation(
                operation_type=TransactionOperationType.delete,
                key="order_2",
                data=str(orderId)),
            TransactionalStateOperation(key="order_2", data=str(orderId))
        ])

        client.delete_state(store_name=DAPR_STORE_NAME, key="order_1")
        logging.basicConfig(level = logging.INFO)
        logging.info('Order requested: ' + str(orderId))
        logging.info('Result: ' + str(result))

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 -- python3 OrderProcessingService.py
// dependencies
package main

import (
    "context"
    "log"
    "math/rand"
    "strconv"
    "time"

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

// code
func main() {
    const STATE_STORE_NAME = "statestore"
    rand.Seed(time.Now().UnixMicro())
    for i := 0; i < 10; i++ {
        orderId := rand.Intn(1000-1) + 1
        client, err := dapr.NewClient()
        if err != nil {
            panic(err)
        }
        defer client.Close()
        ctx := context.Background()
        err = client.SaveState(ctx, STATE_STORE_NAME, "order_1", []byte(strconv.Itoa(orderId)), nil)
        if err != nil {
            panic(err)
        }
        result, err := client.GetState(ctx, STATE_STORE_NAME, "order_1", nil)
        if err != nil {
            panic(err)
        }

        ops := make([]*dapr.StateOperation, 0)
        data1 := "data1"
        data2 := "data2"

        op1 := &dapr.StateOperation{
            Type: dapr.StateOperationTypeUpsert,
            Item: &dapr.SetStateItem{
                Key:   "key1",
                Value: []byte(data1),
            },
        }
        op2 := &dapr.StateOperation{
            Type: dapr.StateOperationTypeDelete,
            Item: &dapr.SetStateItem{
                Key:   "key2",
                Value: []byte(data2),
            },
        }
        ops = append(ops, op1, op2)
        meta := map[string]string{}
        err = client.ExecuteStateTransaction(ctx, STATE_STORE_NAME, meta, ops)

        log.Println("Result after get:", string(result.Value))
        time.Sleep(2 * time.Second)
    }
}

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 go run OrderProcessingService.go
//dependencies
import { DaprClient, HttpMethod, CommunicationProtocolEnum } from '@dapr/dapr';

//code
const daprHost = "127.0.0.1";
var main = function() {
    for(var i=0;i<10;i++) {
        sleep(5000);
        var orderId = Math.floor(Math.random() * (1000 - 1) + 1);
        start(orderId).catch((e) => {
            console.error(e);
            process.exit(1);
        });
    }
}

async function start(orderId) {
    const client = new DaprClient({
        daprHost,
        daprPort: process.env.DAPR_HTTP_PORT,
        communicationProtocol: CommunicationProtocolEnum.HTTP,
    });

    const STATE_STORE_NAME = "statestore";
    //Using Dapr SDK to save and retrieve multiple states
    await client.state.transaction(STATE_STORE_NAME, [
        {
            operation: "upsert",
            request: {
                key: "order_3",
                value: orderId.toString()
            }
        },
        {
            operation: "delete",
            request: {
                key: "order_2"
            }
        }
    ]);
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

main();

위 예시 애플리케이션의 Dapr 사이드카를 시작하려면 다음과 유사한 명령을 실행해요.

dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 npm start

위에서 실행 중인 같은 Dapr 인스턴스로 두 개의 상태 트랜잭션을 수행해요.

curl -X POST -H "Content-Type: application/json" -d '{"operations": [{"operation":"upsert", "request": {"key": "order_1", "value": "250"}}, {"operation":"delete", "request": {"key": "order_2"}}]}' http://localhost:3601/v1.0/state/statestore/transaction

이제 상태 트랜잭션의 결과를 확인해요:

curl -X POST -H "Content-Type: application/json" -d '{"keys":["order_1", "order_2"]}' http://localhost:3601/v1.0/state/statestore/bulk

위에서 실행 중인 같은 Dapr 인스턴스로 statestore에 두 개의 키/값 쌍을 저장해요.

Invoke-RestMethod -Method Post -ContentType 'application/json' -Body '{"operations": [{"operation":"upsert", "request": {"key": "order_1", "value": "250"}}, {"operation":"delete", "request": {"key": "order_2"}}]}' -Uri 'http://localhost:3601/v1.0/state/statestore/transaction'

이제 상태 트랜잭션의 결과를 확인해요:

Invoke-RestMethod -Method Post -ContentType 'application/json' -Body '{"keys":["order_1", "order_2"]}' -Uri 'http://localhost:3601/v1.0/state/statestore/bulk'

다음 단계

  • 전체 State API 레퍼런스를 읽어봐요.
  • Dapr SDK 중 하나를 시도해 봐요.
  • 상태 저장 서비스를 구축해 봐요.

더 알아보기 (Learn more)