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

액터

원문 보기 위키 갱신

액터 (Actors)

Dapr actors 패키지를 사용하면 JavaScript 애플리케이션에서 Dapr 가상 액터와 상호작용할 수 있어요. 아래 예제들은 JavaScript SDK로 가상 액터와 상호작용하는 방법을 보여줘요. Dapr 액터에 대한 더 심층적인 개요는 액터 개요 페이지를 방문해 주세요.

출처: Dapr 문서

본문

사전 준비사항 (Pre-requisites)

  • Dapr CLI 설치
  • 초기화된 Dapr 환경
  • 최신 LTS 버전 이상의 Node
  • JavaScript NPM 패키지 설치

시나리오 (Scenario)

아래 코드 예제들은 Mark Russinovich의 이 영상에서 볼 수 있는 주차장 자리 모니터링 시스템(Parking Garage Spot Monitoring System) 시나리오를 대략적으로 설명해요. 주차장은 수백 개의 주차 공간으로 구성되어 있고, 각 주차 공간에는 중앙 모니터링 시스템에 업데이트를 제공하는 센서가 있어요. 주차 공간 센서(우리의 액터)가 주차 공간이 점유되었는지 비어 있는지를 감지해요. 직접 실행해 보려면 JavaScript SDK 예제 디렉터리에 있는 소스 코드를 클론해 보세요.

액터 인터페이스 (Actor Interface)

액터 인터페이스는 액터 구현과 액터를 호출하는 클라이언트 사이에 공유되는 계약(contract)을 정의해요. 아래 예제에서는 주차장 센서를 위한 인터페이스를 만들었어요. 각 센서에는 주차 공간의 상태를 정의하는 carEnter와 carLeave라는 두 개의 메서드가 있어요:

export default interface ParkingSensorInterface {
carEnter(): Promise<void>;
carLeave(): Promise<void>;
}

액터 구현 (Actor Implementation)

액터 구현은 기본 타입 AbstractActor를 확장하고 액터 인터페이스(여기서는 ParkingSensorInterface)를 구현하는 클래스로 정의해요. 다음 코드는 몇 가지 헬퍼 메서드와 함께 액터 구현을 설명해요.

import { AbstractActor } from "@dapr/dapr";
import ParkingSensorInterface from "./ParkingSensorInterface";

export default class ParkingSensorImpl extends AbstractActor implements ParkingSensorInterface {
async carEnter(): Promise<void> {
// Implementation that updates state that this parking spaces is occupied.
}

async carLeave(): Promise<void> {
// Implementation that updates state that this parking spaces is available.
}

private async getInfo(): Promise<object> {
// Implementation of requesting an update from the parking space sensor.
}

/**
* @override
*/
async onActivate(): Promise<void> {
// Initialization logic called by AbstractActor.
}
}

액터 런타임 구성하기

액터 런타임을 구성하려면 DaprClientOptions를 사용해요. 다양한 파라미터와 기본값은 How-to: Dapr에서 가상 액터 사용하기 문서에 정리되어 있어요. 타임아웃과 인터벌은 time.ParseDuration 문자열 형식으로 지정해야 한다는 점을 기억하세요.

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

// Configure the actor runtime with the DaprClientOptions.
const clientOptions = {
daprHost: daprHost,
daprPort: daprPort,
communicationProtocol: CommunicationProtocolEnum.HTTP,
actor: {
actorIdleTimeout: "1h",
actorScanInterval: "30s",
drainOngoingCallTimeout: "5s",
drainRebalancedActors: true,
reentrancy: {
enabled: true,
maxStackDepth: 32,
},
remindersStoragePartitions: 0,
},
};

// Use the options when creating DaprServer and DaprClient.

// Note, DaprServer creates a DaprClient internally, which needs to be configured with clientOptions.
const server = new DaprServer({ serverHost, serverPort, clientOptions });

const client = new DaprClient(clientOptions);

액터 등록하기

DaprServer 패키지를 사용해서 액터를 초기화하고 등록해요:

import { DaprServer } from "@dapr/dapr";
import ParkingSensorImpl from "./ParkingSensorImpl";

const daprHost = "127.0.0.1";
const daprPort = "50000";
const serverHost = "127.0.0.1";
const serverPort = "50001";

const server = new DaprServer({
serverHost,
serverPort,
clientOptions: {
daprHost,
daprPort,
},
});

await server.actor.init(); // Let the server know we need actors
server.actor.registerActor(ParkingSensorImpl); // Register the actor
await server.start(); // Start the server

// To get the registered actors, you can invoke `getRegisteredActors`:
const resRegisteredActors = await server.actor.getRegisteredActors();
console.log(`Registered Actors: ${JSON.stringify(resRegisteredActors)}`);

액터 메서드 호출하기

액터가 등록된 후에는 ActorProxyBuilder를 사용해서 ParkingSensorInterface를 구현하는 Proxy 객체를 만들어요. Proxy 객체의 메서드를 직접 호출해서 액터 메서드를 호출할 수 있어요. 내부적으로는 액터 API에 네트워크 호출을 하고 결과를 다시 가져오는 것으로 변환돼요.

import { ActorId, DaprClient } from "@dapr/dapr";
import ParkingSensorImpl from "./ParkingSensorImpl";
import ParkingSensorInterface from "./ParkingSensorInterface";

const daprHost = "127.0.0.1";
const daprPort = "50000";

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

// Create a new actor builder. It can be used to create multiple actors of a type.
const builder = new ActorProxyBuilder<ParkingSensorInterface>(ParkingSensorImpl, client);

// Create a new actor instance.
const actor = builder.build(new ActorId("my-actor"));
// Or alternatively, use a random ID
// const actor = builder.build(ActorId.createRandomId());

// Invoke the method.
await actor.carEnter();

액터와 함께 상태 사용하기

import { AbstractActor } from "@dapr/dapr";
import ActorStateInterface from "./ActorStateInterface";

export default class ActorStateExample extends AbstractActor implements ActorStateInterface {
async setState(key: string, value: any): Promise<void> {
await this.getStateManager().setState(key, value);
await this.getStateManager().saveState();
}

async removeState(key: string): Promise<void> {
await this.getStateManager().removeState(key);
await this.getStateManager().saveState();
}

// getState with a specific type
async getState<T>(key: string): Promise<T | null> {
return await this.getStateManager<T>().getState(key);
}

// getState without type as `any`
async getState(key: string): Promise<any> {
return await this.getStateManager().getState(key);
}
}

액터 타이머와 리마인더 (Actor Timers and Reminders)

JS SDK는 타이머나 리마인더를 등록해서 스스로 주기적인 작업을 예약할 수 있는 액터를 지원해요. 타이머와 리마인더의 주요 차이점은, Dapr 액터 런타임이 비활성화(deactivation) 후에는 타이머에 대한 정보를 보존하지 않지만, 리마인더 정보는 Dapr 액터 상태 프로바이더를 사용해서 영속화한다는 점이에요. 이 구분 덕분에 사용자는 가볍지만 상태가 없는 타이머와, 더 많은 리소스를 요구하지만 상태를 가진 리마인더 사이에서 트레이드오프를 선택할 수 있어요. 타이머와 리마인더의 스케줄링 인터페이스는 동일해요. 스케줄링 구성에 대한 더 심층적인 내용은 액터 타이머와 리마인더 문서를 참고해 주세요.

액터 타이머 (Actor Timers)

// ...

const actor = builder.build(new ActorId("my-actor"));

// Register a timer
await actor.registerActorTimer(
"timer-id", // Unique name of the timer.
"cb-method", // Callback method to execute when timer is fired.
Temporal.Duration.from({ seconds: 2 }), // DueTime
Temporal.Duration.from({ seconds: 1 }), // Period
Temporal.Duration.from({ seconds: 1 }), // TTL
50, // State to be sent to timer callback.
);

// Delete the timer
await actor.unregisterActorTimer("timer-id");

액터 리마인더 (Actor Reminders)

// ...

const actor = builder.build(new ActorId("my-actor"));

// Register a reminder, it has a default callback: `receiveReminder`
await actor.registerActorReminder(
"reminder-id", // Unique name of the reminder.
Temporal.Duration.from({ seconds: 2 }), // DueTime
Temporal.Duration.from({ seconds: 1 }), // Period
Temporal.Duration.from({ seconds: 1 }), // TTL
100, // State to be sent to reminder callback.
);

// Delete the reminder
await actor.unregisterActorReminder("reminder-id");

콜백을 처리하려면 액터에서 기본 receiveReminder 구현을 오버라이드해야 해요. 예를 들어 원래 액터 구현에서:

export default class ParkingSensorImpl extends AbstractActor implements ParkingSensorInterface {
// ...

/**
* @override
*/
async receiveReminder(state: any): Promise<void> {
// handle stuff here
}

// ...
}

액터에 대한 전체 가이드는 How-To: Dapr에서 가상 액터 사용하기를 방문해 주세요.

더 알아보기 (Learn more)