서버 (Server)
Dapr 서버를 사용해서 Dapr 사이드카로부터 통신을 받고, 이벤트 구독, 입력 바인딩 수신 등 서버 지향 기능에 접근하는 방법을 알아봐요.
출처: Dapr 문서
본문
소개 (Introduction)
Dapr 서버를 사용하면 Dapr 사이드카로부터 통신을 받고, 이벤트 구독, 입력 바인딩 수신 등 서버 지향 기능에 접근할 수 있어요.
사전 준비사항 (Pre-requisites)
- Dapr CLI 설치
- 초기화된 Dapr 환경
- 최신 LTS 버전 이상의 Node
Dapr JS SDK 설치 및 가져오기
- npm으로 SDK를 설치해요:
npm i @dapr/dapr --save
- 라이브러리를 가져와요:
import { DaprServer, 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 server = new DaprServer({
serverHost,
serverPort,
communicationProtocol: CommunicationProtocolEnum.HTTP, // DaprClient to use same communication protocol as DaprServer, in case DaprClient protocol not mentioned explicitly
clientOptions: {
daprHost,
daprPort,
},
});
// GRPC Example
const server = new DaprServer({
serverHost,
serverPort,
communicationProtocol: CommunicationProtocolEnum.GRPC,
clientOptions: {
daprHost,
daprPort,
},
});
실행하기 (Running)
예제를 실행하려면 Dapr 사이드카와 상호작용하는 두 가지 프로토콜을 사용할 수 있어요: HTTP(기본값) 또는 gRPC.
HTTP 사용하기 (내장 express 웹서버)
import { DaprServer } from "@dapr/dapr";
const server = new DaprServer({
serverHost: appHost,
serverPort: appPort,
clientOptions: {
daprHost,
daprPort,
},
});
// initialize subscribtions, ... before server start
// the dapr sidecar relies on these
await server.start();
dapr run --app-id example-sdk --app-port 50051 --app-protocol http -- npm run start
npm run start:dapr-http
ℹ️ 참고: 여기서 app-port가 필요한 이유는 우리 서버가 여기에 바인딩해야 하기 때문이에요. Dapr은 시작을 마치기 전에 애플리케이션이 이 포트에 바인딩하는지 확인해요.
HTTP 사용하기 (자체 express 웹서버 사용)
Dapr 사이드카에서 애플리케이션으로의 통신을 위한 내장 웹 서버 대신, 자체 인스턴스를 가져올 수도 있어요. 이는 REST API 백엔드를 구축하면서 Dapr을 바로 통합하고 싶은 시나리오에서 유용해요.
참고로, 현재는 express에서만 사용할 수 있어요.
💡 참고: 커스텀 웹서버를 사용하면 SDK가 최대 본문 크기 같은 서버 속성을 구성하고 여기에 새 라우트를 추가해요. 라우트는 애플리케이션과의 충돌을 피하기 위해 그 자체로 고유하지만, 충돌하지 않는다는 보장은 없어요.
import { DaprServer, CommunicationProtocolEnum } from "@dapr/dapr";
import express from "express";
const myApp = express();
myApp.get("/my-custom-endpoint", (req, res) => {
res.send({ msg: "My own express app!" });
});
const daprServer = new DaprServer({
serverHost: "127.0.0.1", // App Host
serverPort: "50002", // App Port
serverHttp: myApp,
clientOptions: {
daprHost
daprPort
}
});
// Initialize subscriptions before the server starts, the Dapr sidecar uses it.
// This will also initialize the app server itself (removing the need for `app.listen` to be called).
await daprServer.start();
위 구성을 마치면 평소처럼 커스텀 엔드포인트를 호출할 수 있어요:
const res = await fetch(`http://127.0.0.1:50002/my-custom-endpoint`);
const json = await res.json();
gRPC 사용하기
HTTP가 기본값이므로 gRPC를 사용하려면 통신 프로토콜을 조정해야 해요. 클라이언트나 서버 생성자에 추가 인자를 전달해서 이렇게 할 수 있어요.
import { DaprServer, CommunicationProtocol } from "@dapr/dapr";
const server = new DaprServer({
serverHost: appHost,
serverPort: appPort,
communicationProtocol: CommunicationProtocolEnum.GRPC,
clientOptions: {
daprHost,
daprPort,
},
});
// initialize subscribtions, ... before server start
// the dapr sidecar relies on these
await server.start();
dapr run --app-id example-sdk --app-port 50051 --app-protocol grpc -- npm run start
npm run start:dapr-grpc
ℹ️ 참고: 여기서 app-port가 필요한 이유는 우리 서버가 여기에 바인딩해야 하기 때문이에요. Dapr은 시작을 마치기 전에 애플리케이션이 이 포트에 바인딩하는지 확인해요.
빌딩 블록 (Building blocks)
JavaScript 서버 SDK는 사이드카에서 앱으로의 기능에 초점을 맞춘 모든 Dapr 빌딩 블록과 인터페이스할 수 있게 해줘요.
호출 API (Invocation API)
호출 수신하기
import { DaprServer, DaprInvokerCallbackContent } 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 "
async function start() {
const server = new DaprServer({
serverHost,
serverPort,
clientOptions: {
daprHost,
daprPort,
},
});
const callbackFunction = (data: DaprInvokerCallbackContent) => {
console.log("Received body: ", data.body);
console.log("Received metadata: ", data.metadata);
console.log("Received query: ", data.query);
console.log("Received headers: ", data.headers); // only available in HTTP
};
await server.invoker.listen("hello-world", callbackFunction, { method: HttpMethod.GET });
// You can now invoke the service with your app id and method "hello-world"
await server.start();
}
start().catch((e) => {
console.error(e);
process.exit(1);
});
서비스 호출에 대한 전체 가이드는 How-To: 서비스 호출을 참고해 주세요.
PubSub API
메시지 구독하기
토픽에서 메시지를 받을 수 있도록 유연성을 제공하는 여러 가지 방식으로 메시지 구독을 할 수 있어요:
subscribe메서드를 통한 직접 구독subscribeWithOptions메서드를 통한 옵션을 포함한 직접 구독susbcribeOnEvent메서드를 통한 이후 구독
이벤트가 도착할 때마다 그 본문을 data로, 헤더를 headers로 전달해요. 헤더에는 이벤트 게시자의 속성(예: IoT Hub의 디바이스 ID)이 포함될 수 있어요.
Dapr은 시작 시 구독이 설정되어 있어야 하지만, JS SDK에서는 이후에도 이벤트 핸들러를 추가할 수 있어 프로그래밍의 유연성을 제공해요.
아래에 예시가 제공돼 있어요.
import { DaprServer } 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 "
async function start() {
const server = new DaprServer({
serverHost,
serverPort,
clientOptions: {
daprHost,
daprPort,
},
});
const pubSubName = "my-pubsub-name";
const topic = "topic-a";
// Configure Subscriber for a Topic
// Method 1: Direct subscription through the `subscribe` method
await server.pubsub.subscribe(pubSubName, topic, async (data: any, headers: object) =>
console.log(`Received Data: ${JSON.stringify(data)} with headers: ${JSON.stringify(headers)}`),
);
// Method 2: Direct susbcription with options through the `subscribeWithOptions` method
await server.pubsub.subscribeWithOptions(pubSubName, topic, {
callback: async (data: any, headers: object) =>
console.log(`Received Data: ${JSON.stringify(data)} with headers: ${JSON.stringify(headers)}`),
});
// Method 3: Subscription afterwards through the `susbcribeOnEvent` method
// Note: we use default, since if no route was passed (empty options) we utilize "default" as the route name
await server.pubsub.subscribeWithOptions("pubsub-redis", "topic-options-1", {});
server.pubsub.subscribeToRoute("pubsub-redis", "topic-options-1", "default", async (data: any, headers: object) => {
console.log(`Received Data: ${JSON.stringify(data)} with headers: ${JSON.stringify(headers)}`);
});
// Start the server
await server.start();
}
상태 연산의 전체 목록은 How-To: 게시 & 구독을 참고해 주세요.
SUCCESS/RETRY/DROP 상태로 구독하기
Dapr은 메시지가 처리된 후 어떤 일이 일어나야 하는지 지정하기 위한 재시도 로직 상태 코드를 지원해요.
⚠️ JS SDK는 같은 토픽에서 여러 콜백을 허용하며, 상태 우선순위를 RETRY > DROP > SUCCESS로 처리하고 기본값은 SUCCESS예요.
⚠️ RETRY 메시지를 처리하려면 애플리케이션에 resiliency를 구성해야 해요.
JS SDK에서는 이러한 메시지를 DaprPubSubStatusEnum 열거형으로 지원해요. Dapr이 재시도하도록 하려면 Resiliency 정책도 구성해요.
components/resiliency.yaml
apiVersion: dapr.io/v1alpha1
kind: Resiliency
metadata:
name: myresiliency
spec:
policies:
retries:
DefaultComponentInboundRetryPolicy:
policy: constant
duration: 500ms
maxRetries: 10
targets:
components:
messagebus:
inbound:
retry: DefaultComponentInboundRetryPolicy
src/index.ts
import { DaprServer, DaprPubSubStatusEnum } 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 "
async function start() {
const server = new DaprServer({
serverHost,
serverPort,
clientOptions: {
daprHost,
daprPort,
},
});
const pubSubName = "my-pubsub-name";
const topic = "topic-a";
// Process a message successfully
await server.pubsub.subscribe(pubSubName, topic, async (data: any, headers: object) => {
return DaprPubSubStatusEnum.SUCCESS;
});
// Retry a message
// Note: this example will keep on retrying to deliver the message
// Note 2: each component can have their own retry configuration
// e.g., https://docs.dapr.io/reference/components-reference/supported-pubsub/setup-redis-pubsub/
await server.pubsub.subscribe(pubSubName, topic, async (data: any, headers: object) => {
return DaprPubSubStatusEnum.RETRY;
});
// Drop a message
await server.pubsub.subscribe(pubSubName, topic, async (data: any, headers: object) => {
return DaprPubSubStatusEnum.DROP;
});
// Start the server
await server.start();
}
규칙 기반 메시지 구독하기
Dapr은 규칙에 따라 메시지를 서로 다른 핸들러(라우트)로 라우팅하는 것을 지원해요.
예를 들어 메시지의 "type"에 따라 메시지를 처리해야 하는 애플리케이션을 Dapr로 작성한다면, 기본 라우트가 handlerDefault인 상태에서 메시지를 handlerType1과 handlerType2라는 서로 다른 라우트로 보낼 수 있어요.
import { DaprServer } 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 "
async function start() {
const server = new DaprServer({
serverHost,
serverPort,
clientOptions: {
daprHost,
daprPort,
},
});
const pubSubName = "my-pubsub-name";
const topic = "topic-a";
// Configure Subscriber for a Topic with rule set
// Note: the default route and match patterns are optional
await server.pubsub.subscribe("pubsub-redis", "topic-1", {
default: "/default",
rules: [
{
match: `event.type == "my-type-1"`,
path: "/type-1",
},
{
match: `event.type == "my-type-2"`,
path: "/type-2",
},
],
});
// Add handlers for each route
server.pubsub.subscribeToRoute("pubsub-redis", "topic-1", "default", async (data) => {
console.log(`Handling Default`);
});
server.pubsub.subscribeToRoute("pubsub-redis", "topic-1", "type-1", async (data) => {
console.log(`Handling Type 1`);
});
server.pubsub.subscribeToRoute("pubsub-redis", "topic-1", "type-2", async (data) => {
console.log(`Handling Type 2`);
});
// Start the server
await server.start();
}
와일드카드로 구독하기
인기 있는 와일드카드 *와 +가 지원되며(pubsub 컴포넌트가 이를 지원하는지 확인해 주세요), 다음과 같이 구독할 수 있어요:
import { DaprServer } 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 "
async function start() {
const server = new DaprServer({
serverHost,
serverPort,
clientOptions: {
daprHost,
daprPort,
},
});
const pubSubName = "my-pubsub-name";
// * Wildcard
await server.pubsub.subscribe(pubSubName, "/events/*", async (data: any, headers: object) =>
console.log(`Received Data: ${JSON.stringify(data)}`),
);
// + Wildcard
await server.pubsub.subscribe(pubSubName, "/events/+/temperature", async (data: any, headers: object) =>
console.log(`Received Data: ${JSON.stringify(data)}`),
);
// Start the server
await server.start();
}
메시지 벌크 구독하기
벌크 구독(Bulk Subscription)이 지원되며 다음 API를 통해 사용할 수 있어요:
subscribeBulk메서드를 통한 벌크 구독:maxMessagesCount와maxAwaitDurationMs는 선택 사항이며, 제공하지 않으면 관련 컴포넌트의 기본값이 사용돼요.
메시지를 수신하는 동안 애플리케이션은 Dapr로부터 벌크로 메시지를 받아요. 하지만 일반 구독과 마찬가지로 콜백 함수는 한 번에 하나의 메시지를 받고, 사용자는 DaprPubSubStatusEnum 값을 반환해서 메시지를 성공으로 처리하거나, 재시도하거나, 버릴(drop) 수 있어요. 기본 동작은 성공 응답을 반환하는 거예요.
자세한 내용은 이 문서를 참고해 주세요.
import { DaprServer } from "@dapr/dapr";
const pubSubName = "orderPubSub";
const topic = "topicbulk";
const daprHost = process.env.DAPR_HOST || "127.0.0.1";
const daprHttpPort = process.env.DAPR_HTTP_PORT || "3502";
const serverHost = process.env.SERVER_HOST || "127.0.0.1";
const serverPort = process.env.APP_PORT || 5001;
async function start() {
const server = new DaprServer({
serverHost,
serverPort,
clientOptions: {
daprHost,
daprPort: daprHttpPort,
},
});
// Publish multiple messages to a topic with default config.
await client.pubsub.subscribeBulk(pubSubName, topic, (data) =>
console.log("Subscriber received: " + JSON.stringify(data)),
);
// Publish multiple messages to a topic with specific maxMessagesCount and maxAwaitDurationMs.
await client.pubsub.subscribeBulk(
pubSubName,
topic,
(data) => {
console.log("Subscriber received: " + JSON.stringify(data));
return DaprPubSubStatusEnum.SUCCESS; // If App doesn't return anything, the default is SUCCESS. App can also return RETRY or DROP based on the incoming message.
},
{
maxMessagesCount: 100,
maxAwaitDurationMs: 40,
},
);
}
데드 레터 토픽 (Dead Letter Topics)
Dapr은 데드 레터 토픽을 지원해요. 즉, 메시지가 처리에 실패하면 데드 레터 큐로 보내진다는 뜻이에요. 예를 들어 /my-queue에서 메시지 처리가 실패하면 /my-queue-failed로 보내져요.
subscribeWithOptions 메서드에서 다음 옵션을 사용할 수 있어요:
- deadletterTopic: 데드 레터 토픽 이름을 지정해요 (참고: 제공하지 않으면
deadletter라는 이름으로 하나를 만들어요) - deadletterCallback: 데드 레터의 핸들러로 트리거할 메서드예요
JS SDK에서 데드레터 지원을 구현하는 방법은 두 가지예요:
- deadletterCallback을 옵션으로 전달하기
- subscribeToRoute로 라우트를 수동으로 구독하기
아래에 예시가 제공돼 있어요.
import { DaprServer } 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 "
async function start() {
const server = new DaprServer({
serverHost,
serverPort,
clientOptions: {
daprHost,
daprPort,
},
});
const pubSubName = "my-pubsub-name";
// Method 1 (direct subscribing through subscribeWithOptions)
await server.pubsub.subscribeWithOptions("pubsub-redis", "topic-options-5", {
callback: async (data: any) => {
throw new Error("Triggering Deadletter");
},
deadLetterCallback: async (data: any) => {
console.log("Handling Deadletter message");
},
});
// Method 2 (subscribe afterwards)
await server.pubsub.subscribeWithOptions("pubsub-redis", "topic-options-1", {
deadletterTopic: "my-deadletter-topic",
});
server.pubsub.subscribeToRoute("pubsub-redis", "topic-options-1", "default", async () => {
throw new Error("Triggering Deadletter");
});
server.pubsub.subscribeToRoute("pubsub-redis", "topic-options-1", "my-deadletter-topic", async () => {
console.log("Handling Deadletter message");
});
// Start server
await server.start();
}
바인딩 API (Bindings API)
입력 바인딩 수신하기
import { DaprServer } from "@dapr/dapr";
const daprHost = "127.0.0.1";
const daprPort = "3500";
const serverHost = "127.0.0.1";
const serverPort = "5051";
async function start() {
const server = new DaprServer({
serverHost,
serverPort,
clientOptions: {
daprHost,
daprPort,
},
});
const bindingName = "my-binding-name";
const response = await server.binding.receive(bindingName, async (data: any) =>
console.log(`Got Data: ${JSON.stringify(data)}`),
);
await server.start();
}
start().catch((e) => {
console.error(e);
process.exit(1);
});
출력 바인딩에 대한 전체 가이드는 How-To: 바인딩 사용하기를 참고해 주세요.
구성 API (Configuration API)
💡 구성 API는 현재 gRPC를 통해서만 사용할 수 있어요.
구성 값 가져오기
import { DaprServer } from "@dapr/dapr";
const daprHost = "127.0.0.1";
const daprPort = "3500";
const serverHost = "127.0.0.1";
const serverPort = "5051";
async function start() {
const client = new DaprClient({
daprHost,
daprPort,
communicationProtocol: CommunicationProtocolEnum.GRPC,
});
const config = await client.configuration.get("config-redis", ["myconfigkey1", "myconfigkey2"]);
}
start().catch((e) => {
console.error(e);
process.exit(1);
});
키 변경 구독하기
import { DaprServer } from "@dapr/dapr";
const daprHost = "127.0.0.1";
const daprPort = "3500";
const serverHost = "127.0.0.1";
const serverPort = "5051";
async function start() {
const client = new DaprClient({
daprHost,
daprPort,
communicationProtocol: CommunicationProtocolEnum.GRPC,
});
const stream = await client.configuration.subscribeWithKeys("config-redis", ["myconfigkey1", "myconfigkey2"], () => {
// Received a key update
});
// When you are ready to stop listening, call the following
await stream.close();
}
start().catch((e) => {
console.error(e);
process.exit(1);
});
관련 링크 (Related links)
- JavaScript SDK 예제