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

클라이언트

원문 보기 위키 갱신

클라이언트 (Client)

Dapr 클라이언트를 사용해서 Dapr 사이드카와 통신하고, 이벤트 게시, 출력 바인딩 호출, 상태 관리, 비밀 관리 등 클라이언트 지향 기능에 접근하는 방법을 알아봐요.

출처: Dapr 문서

본문

소개 (Introduction)

Dapr 클라이언트를 사용하면 Dapr 사이드카와 통신하고 이벤트 게시, 출력 바인딩 호출, 상태 관리, 비밀 관리 등 클라이언트 지향 기능에 접근할 수 있어요.

사전 준비사항 (Pre-requisites)

  • Dapr CLI 설치
  • 초기화된 Dapr 환경
  • 최신 LTS 버전 이상의 Node.js

Dapr JS SDK 설치 및 가져오기

  • npm으로 SDK를 설치해요:
npm i @dapr/dapr --save
  • 라이브러리를 가져와요:
import { DaprClient, DaprServer, HttpMethod, CommunicationProtocolEnum } from "@dapr/dapr";

const daprHost = "127.0.0.1"; // Dapr Sidecar Host
const daprPort = "3500"; // Dapr Sidecar Port of this Example Server
const serverHost = "127.0.0.1"; // App Host of this Example Server
const serverPort = "50051"; // App Port of this Example Server

// HTTP Example
const client = new DaprClient({ daprHost, daprPort });

// GRPC Example
const client = new DaprClient({ daprHost, daprPort, communicationProtocol: CommunicationProtocolEnum.GRPC });

실행하기 (Running)

예제를 실행하려면 Dapr 사이드카와 상호작용하는 두 가지 프로토콜을 사용할 수 있어요: HTTP(기본값) 또는 gRPC.

HTTP 사용하기 (기본값)

import { DaprClient } from "@dapr/dapr";
const client = new DaprClient({ daprHost, daprPort });

dapr run --app-id example-sdk --app-protocol http -- npm run start


npm run start:dapr-http

gRPC 사용하기

HTTP가 기본값이므로 gRPC를 사용하려면 통신 프로토콜을 조정해야 해요. 클라이언트나 서버 생성자에 추가 인자를 전달해서 이렇게 할 수 있어요.

import { DaprClient, CommunicationProtocol } from "@dapr/dapr";
const client = new DaprClient({ daprHost, daprPort, communicationProtocol: CommunicationProtocol.GRPC });

dapr run --app-id example-sdk --app-protocol grpc -- npm run start


npm run start:dapr-grpc

환경 변수

Dapr 사이드카 엔드포인트 DAPR_HTTP_ENDPOINT와 DAPR_GRPC_ENDPOINT 환경 변수를 사용해서 Dapr 사이드카의 HTTP 및 gRPC 엔드포인트를 각각 설정할 수 있어요. 이 변수들이 설정되면 생성자의 options 인자에 daprHost와 daprPort를 설정할 필요가 없어요. 클라이언트가 제공된 엔드포인트에서 자동으로 파싱해요.

import { DaprClient, CommunicationProtocol } from "@dapr/dapr";

// Using HTTP, when DAPR_HTTP_ENDPOINT is set
const client = new DaprClient();

// Using gRPC, when DAPR_GRPC_ENDPOINT is set
const client = new DaprClient({ communicationProtocol: CommunicationProtocol.GRPC });

환경 변수가 설정되어 있더라도 생성자에 daprHost와 daprPort 값이 전달되면, 후자가 환경 변수보다 우선해요. Dapr API 토큰 DAPR_API_TOKEN 환경 변수를 사용해서 Dapr API 토큰을 설정할 수 있어요. 이 변수가 설정되면 생성자의 options 인자에 daprApiToken을 설정할 필요가 없어요. 클라이언트가 자동으로 가져와요.

일반 (General)

본문 크기 늘리기

DaprClient의 옵션을 사용해서 애플리케이션이 사이드카와 통신할 때 사용하는 본문 크기를 늘릴 수 있어요.

import { DaprClient, CommunicationProtocol } from "@dapr/dapr";

// Allow a body size of 10Mb to be used
// The default is 4Mb
const client = new DaprClient({
daprHost,
daprPort,
communicationProtocol: CommunicationProtocol.HTTP,
maxBodySizeMb: 10,
});

요청 프록시하기

요청을 프록시함으로써 서비스 디스커버리, 로깅 등 Dapr이 사이드카 아키텍처와 함께 가져오는 독특한 기능들을 활용해서 gRPC 서비스를 즉시 "업그레이드"할 수 있어요. 이 gRPC 프록시 기능은 커뮤니티 콜 41에서 시연되었어요.

프록시 만들기

gRPC 프록시를 수행하려면 client.proxy.create() 메서드를 호출해서 프록시를 만들면 돼요:

// As always, create a client to our dapr sidecar
// this client takes care of making sure the sidecar is started, that we can communicate, ...
const clientSidecar = new DaprClient({ daprHost, daprPort, communicationProtocol: CommunicationProtocol.GRPC });

// Create a Proxy that allows us to use our gRPC code
const clientProxy = await clientSidecar.proxy.create<GreeterClient>(GreeterClient);

이제 GreeterClient 인터페이스(여기서는 Hello World 예제에서 가져온 것)에 정의된 메서드를 호출할 수 있어요.

내부 동작 (Behind the Scenes - 기술적 동작)

  • gRPC 서비스가 Dapr에서 시작돼요. --app-port를 통해 이 gRPC 서버가 실행 중인 포트를 Dapr에 알려주고, --app-id <APP_ID_HERE>로 고유한 Dapr 앱 ID를 부여해요.
  • 이제 사이드카에 연결하는 클라이언트를 통해 Dapr 사이드카를 호출할 수 있어요.
  • Dapr 사이드카를 호출하면서, Dapr에서 부팅된 gRPC 서버(예제에서는 server) 값을 가진 dapr-app-id라는 메타데이터 키를 제공해요.
  • Dapr은 이제 구성된 gRPC 서버로 호출을 전달해요.

빌딩 블록 (Building blocks)

JavaScript 클라이언트 SDK는 클라이언트에서 사이드카로의 기능에 초점을 맞춘 모든 Dapr 빌딩 블록과 인터페이스할 수 있게 해줘요.

호출 API (Invocation API)

서비스 호출하기

import { DaprClient, HttpMethod } from "@dapr/dapr";

const daprHost = "127.0.0.1";
const daprPort = "3500";

async function start() {
const client = new DaprClient({ daprHost, daprPort });

const serviceAppId = "my-app-id";
const serviceMethod = "say-hello";

// POST Request
const response = await client.invoker.invoke(serviceAppId, serviceMethod, HttpMethod.POST, { hello: "world" });

// POST Request with headers
const response = await client.invoker.invoke(
serviceAppId,
serviceMethod,
HttpMethod.POST,
{ hello: "world" },
{ headers: { "X-User-ID": "123" } },
);

// GET Request
const response = await client.invoker.invoke(serviceAppId, serviceMethod, HttpMethod.GET);
}

start().catch((e) => {
console.error(e);
process.exit(1);
});

서비스 호출에 대한 전체 가이드는 How-To: 서비스 호출을 참고해 주세요.

상태 관리 API (State Management API)

애플리케이션 상태 저장, 조회, 삭제

import { DaprClient } from "@dapr/dapr";

const daprHost = "127.0.0.1";
const daprPort = "3500";

async function start() {
const client = new DaprClient({ daprHost, daprPort });

const serviceStoreName = "my-state-store-name";

// Save State
const response = await client.state.save(
serviceStoreName,
[
{
key: "first-key-name",
value: "hello",
metadata: {
foo: "bar",
},
},
{
key: "second-key-name",
value: "world",
},
],
{
metadata: {
ttlInSeconds: "3", // this should override the ttl in the state item
},
},
);

// Get State
const response = await client.state.get(serviceStoreName, "first-key-name");

// Get Bulk State
const response = await client.state.getBulk(serviceStoreName, ["first-key-name", "second-key-name"]);

// State Transactions
await client.state.transaction(serviceStoreName, [
{
operation: "upsert",
request: {
key: "first-key-name",
value: "new-data",
},
},
{
operation: "delete",
request: {
key: "second-key-name",
},
},
]);

// Delete State
const response = await client.state.delete(serviceStoreName, "first-key-name");
}

start().catch((e) => {
console.error(e);
process.exit(1);
});

상태 연산의 전체 목록은 How-To: 상태 조회 및 저장을 참고해 주세요.

상태 조회 API (Query State API)

import { DaprClient } from "@dapr/dapr";

async function start() {
const client = new DaprClient({ daprHost, daprPort });

const res = await client.state.query("state-mongodb", {
filter: {
OR: [
{
EQ: { "person.org": "Dev Ops" },
},
{
AND: [
{
EQ: { "person.org": "Finance" },
},
{
IN: { state: ["CA", "WA"] },
},
],
},
],
},
sort: [
{
key: "state",
order: "DESC",
},
],
page: {
limit: 10,
},
});

console.log(res);
}

start().catch((e) => {
console.error(e);
process.exit(1);
});

PubSub API

메시지 게시하기

import { DaprClient } from "@dapr/dapr";

const daprHost = "127.0.0.1";
const daprPort = "3500";

async function start() {
const client = new DaprClient({ daprHost, daprPort });

const pubSubName = "my-pubsub-name";
const topic = "topic-a";

// Publish message to topic as text/plain
// Note, the content type is inferred from the message type unless specified explicitly
const response = await client.pubsub.publish(pubSubName, topic, "hello, world!");
// If publish fails, response contains the error
console.log(response);

// Publish message to topic as application/json
await client.pubsub.publish(pubSubName, topic, { hello: "world" });

// Publish a JSON message as plain text
const options = { contentType: "text/plain" };
await client.pubsub.publish(pubSubName, topic, { hello: "world" }, options);

// Publish message to topic as application/cloudevents+json
// You can also use the cloudevent SDK to create cloud events https://github.com/cloudevents/sdk-javascript
const cloudEvent = {
specversion: "1.0",
source: "/some/source",
type: "example",
id: "1234",
};
await client.pubsub.publish(pubSubName, topic, cloudEvent);

// Publish a cloudevent as raw payload
const options = { metadata: { rawPayload: true } };
await client.pubsub.publish(pubSubName, topic, "hello, world!", options);

// Publish multiple messages to a topic as text/plain
await client.pubsub.publishBulk(pubSubName, topic, ["message 1", "message 2", "message 3"]);

// Publish multiple messages to a topic as application/json
await client.pubsub.publishBulk(pubSubName, topic, [
{ hello: "message 1" },
{ hello: "message 2" },
{ hello: "message 3" },
]);

// Publish multiple messages with explicit bulk publish messages
const bulkPublishMessages = [
{
entryID: "entry-1",
contentType: "application/json",
event: { hello: "foo message 1" },
},
{
entryID: "entry-2",
contentType: "application/cloudevents+json",
event: { ...cloudEvent, data: "foo message 2", datacontenttype: "text/plain" },
},
{
entryID: "entry-3",
contentType: "text/plain",
event: "foo message 3",
},
];
await client.pubsub.publishBulk(pubSubName, topic, bulkPublishMessages);
}

start().catch((e) => {
console.error(e);
process.exit(1);
});

바인딩 API (Bindings API)

출력 바인딩 호출하기

출력 바인딩 (Output Bindings)

import { DaprClient } from "@dapr/dapr";

const daprHost = "127.0.0.1";
const daprPort = "3500";

async function start() {
const client = new DaprClient({ daprHost, daprPort });

const bindingName = "my-binding-name";
const bindingOperation = "create";
const message = { hello: "world" };

const response = await client.binding.send(bindingName, bindingOperation, message);
}

start().catch((e) => {
console.error(e);
process.exit(1);
});

출력 바인딩에 대한 전체 가이드는 How-To: 바인딩 사용하기를 참고해 주세요.

비밀 API (Secret API)

비밀 조회하기

import { DaprClient } from "@dapr/dapr";

const daprHost = "127.0.0.1";
const daprPort = "3500";

async function start() {
const client = new DaprClient({ daprHost, daprPort });

const secretStoreName = "my-secret-store";
const secretKey = "secret-key";

// Retrieve a single secret from secret store
const response = await client.secret.get(secretStoreName, secretKey);

// Retrieve all secrets from secret store
const response = await client.secret.getBulk(secretStoreName);
}

start().catch((e) => {
console.error(e);
process.exit(1);
});

비밀에 대한 전체 가이드는 How-To: 비밀 조회하기를 참고해 주세요.

구성 API (Configuration API)

구성 키 조회하기

import { DaprClient } from "@dapr/dapr";

const daprHost = "127.0.0.1";

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

const config = await client.configuration.get("config-store", ["key1", "key2"]);
console.log(config);
}

start().catch((e) => {
console.error(e);
process.exit(1);
});

샘플 출력:

{
items: {
key1: { key: 'key1', value: 'foo', version: '', metadata: {} },
key2: { key: 'key2', value: 'bar2', version: '', metadata: {} }
}
}

구성 업데이트 구독하기

import { DaprClient } from "@dapr/dapr";

const daprHost = "127.0.0.1";

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

// Subscribes to config store changes for keys "key1" and "key2"
const stream = await client.configuration.subscribeWithKeys("config-store", ["key1", "key2"], async (data) => {
console.log("Subscribe received updates from config store: ", data);
});

// Wait for 60 seconds and unsubscribe.
await new Promise((resolve) => setTimeout(resolve, 60000));
stream.stop();
}

start().catch((e) => {
console.error(e);
process.exit(1);
});

샘플 출력:

Subscribe received updates from config store: {
items: { key2: { key: 'key2', value: 'bar', version: '', metadata: {} } }
}
Subscribe received updates from config store: {
items: { key1: { key: 'key1', value: 'foobar', version: '', metadata: {} } }
}

암호화 API (Cryptography API)

암호화 API에 대한 지원은 JavaScript SDK에서 gRPC 클라이언트에서만 사용할 수 있어요.

import { createReadStream, createWriteStream } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { pipeline } from "node:stream/promises";

import { DaprClient, CommunicationProtocolEnum } from "@dapr/dapr";

const daprHost = "127.0.0.1";
const daprPort = "50050"; // Dapr Sidecar Port of this example server

async function start() {
const client = new DaprClient({
daprHost,
daprPort,
communicationProtocol: CommunicationProtocolEnum.GRPC,
});

// Encrypt and decrypt a message using streams
await encryptDecryptStream(client);

// Encrypt and decrypt a message from a buffer
await encryptDecryptBuffer(client);
}

async function encryptDecryptStream(client: DaprClient) {
// First, encrypt the message
console.log("== Encrypting message using streams");
console.log("Encrypting plaintext.txt to ciphertext.out");

await pipeline(
createReadStream("plaintext.txt"),
await client.crypto.encrypt({
componentName: "crypto-local",
keyName: "symmetric256",
keyWrapAlgorithm: "A256KW",
}),
createWriteStream("ciphertext.out"),
);

// Decrypt the message
console.log("== Decrypting message using streams");
console.log("Encrypting ciphertext.out to plaintext.out");
await pipeline(
createReadStream("ciphertext.out"),
await client.crypto.decrypt({
componentName: "crypto-local",
}),
createWriteStream("plaintext.out"),
);
}

async function encryptDecryptBuffer(client: DaprClient) {
// Read "plaintext.txt" so we have some content
const plaintext = await readFile("plaintext.txt");

// First, encrypt the message
console.log("== Encrypting message using buffers");

const ciphertext = await client.crypto.encrypt(plaintext, {
componentName: "crypto-local",
keyName: "my-rsa-key",
keyWrapAlgorithm: "RSA",
});

await writeFile("test.out", ciphertext);

// Decrypt the message
console.log("== Decrypting message using buffers");
const decrypted = await client.crypto.decrypt(ciphertext, {
componentName: "crypto-local",
});

// The contents should be equal
if (plaintext.compare(decrypted) !== 0) {
throw new Error("Decrypted message does not match original message");
}
}

start().catch((e) => {
console.error(e);
process.exit(1);
});

암호화에 대한 전체 가이드는 How-To: 암호화를 참고해 주세요.

분산 락 API (Distributed Lock API)

Try Lock 및 Unlock API

import { CommunicationProtocolEnum, DaprClient } from "@dapr/dapr";
import { LockStatus } from "@dapr/dapr/types/lock/UnlockResponse";

const daprHost = "127.0.0.1";
const daprPortDefault = "3500";

async function start() {
const client = new DaprClient({ daprHost, daprPort });

const storeName = "redislock";
const resourceId = "resourceId";
const lockOwner = "owner1";
let expiryInSeconds = 1000;

console.log(`Acquiring lock on ${storeName}, ${resourceId} as owner: ${lockOwner}`);
const lockResponse = await client.lock.lock(storeName, resourceId, lockOwner, expiryInSeconds);
console.log(lockResponse);

console.log(`Unlocking on ${storeName}, ${resourceId} as owner: ${lockOwner}`);
const unlockResponse = await client.lock.unlock(storeName, resourceId, lockOwner);
console.log("Unlock API response: " + getResponseStatus(unlockResponse.status));
}

function getResponseStatus(status: LockStatus) {
switch (status) {
case LockStatus.Success:
return "Success";
case LockStatus.LockDoesNotExist:
return "LockDoesNotExist";
case LockStatus.LockBelongsToOthers:
return "LockBelongsToOthers";
default:
return "InternalError";
}
}

start().catch((e) => {
console.error(e);
process.exit(1);
});

분산 락에 대한 전체 가이드는 How-To: 분산 락 사용하기를 참고해 주세요.

워크플로 API (Workflow API)

워크플로 관리

import { DaprClient } from "@dapr/dapr";

async function start() {
const client = new DaprClient();

// Start a new workflow instance
const instanceId = await client.workflow.start("OrderProcessingWorkflow", {
Name: "Paperclips",
TotalCost: 99.95,
Quantity: 4,
});
console.log(`Started workflow instance ${instanceId}`);

// Get a workflow instance
const workflow = await client.workflow.get(instanceId);
console.log(
`Workflow ${workflow.workflowName}, created at ${workflow.createdAt.toUTCString()}, has status ${
workflow.runtimeStatus
}`,
);
console.log(`Additional properties: ${JSON.stringify(workflow.properties)}`);

// Pause a workflow instance
await client.workflow.pause(instanceId);
console.log(`Paused workflow instance ${instanceId}`);

// Resume a workflow instance
await client.workflow.resume(instanceId);
console.log(`Resumed workflow instance ${instanceId}`);

// Terminate a workflow instance
await client.workflow.terminate(instanceId);
console.log(`Terminated workflow instance ${instanceId}`);

// Purge a workflow instance
await client.workflow.purge(instanceId);
console.log(`Purged workflow instance ${instanceId}`);
}

start().catch((e) => {
console.error(e);
process.exit(1);
});
  • JavaScript SDK 예제

더 알아보기 (Learn more)