Quickstart: Actors
Dapr의 Actors 빌딩 블록으로 시작해 봐요.
Dapr의 Actors 빌딩 블록을 살펴볼게요. 이 Quickstart에서 스마트 디바이스 마이크로서비스와 간단한 콘솔 클라이언트를 실행해서 Dapr Actors의 상태 저장형 객체 패턴을 보여줄 거예요.
현재 이 actors quickstart는 .NET SDK로 체험할 수 있어요.
- .NET
.NET actors quickstart를 간단히 요약하면 이래요.
- SmartDevice.Service 마이크로서비스를 사용해서 다음을 호스팅해요.
- SmokeDetectorActor 연기 감지기 객체 2개
- 스마트 디바이스를 명령하고 제어하는 ControllerActor 객체
- SmartDevice.Client 콘솔 앱에서 클라이언트 앱이 각 actor 또는 컨트롤러와 상호작용해서 집합적으로 작업을 수행해요.
- SmartDevice.Interfaces에는 서비스 앱과 클라이언트 앱이 공유하는 인터페이스와 데이터 타입이 들어 있어요.
출처: Dapr 문서
본문
사전 조건 (Pre-requisites)
이 예제에 필요한 것들:
-
Dapr CLI와 초기화된 환경.
-
Docker Desktop.
-
.NET 8 설치.
참고: .NET 6은 이 릴리스에서 Dapr .NET SDK 패키지가 지원하는 최소 .NET 버전이에요. Dapr v1.16 이상에서는 .NET 8과 .NET 9만 지원됩니다.
1단계: 환경 설정하기
Quickstarts 저장소에 제공된 샘플을 클론해요.
git clone https://github.com/dapr/quickstarts.git
2단계: 서비스 앱 실행하기
새 터미널 창에서 actors/csharp/sdk/service 디렉터리로 이동하고 의존성을 복원해요.
cd actors/csharp/sdk/service
dotnet build
SmartDevice.Service를 실행해요. 이 앱은 서비스 자체와 Dapr sidecar를 함께 시작해요.
dapr run --app-id actorservice --app-port 5001 --dapr-http-port 3500 --resources-path ../../../resources -- dotnet run --urls=http://localhost:5001/
예상 출력:
== APP == info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
== APP == Request starting HTTP/1.1 GET http://127.0.0.1:5001/healthz - -
== APP == info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
== APP == Executing endpoint 'Dapr Actors Health Check'
== APP == info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
== APP == Executed endpoint 'Dapr Actors Health Check'
== APP == info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
== APP == Request finished HTTP/1.1 GET http://127.0.0.1:5001/healthz - - - 200 - text/plain 5.2599ms
3단계: 클라이언트 앱 실행하기
새 터미널 인스턴스에서 actors/csharp/sdk/client 디렉터리로 이동하고 의존성을 설치해요.
cd ./actors/csharp/sdk/client
dotnet build
SmartDevice.Client 앱을 실행해요.
dapr run --app-id actorclient -- dotnet run
예상 출력:
== APP == Startup up...
== APP == Calling SetDataAsync on SmokeDetectorActor:1...
== APP == Got response: Success
== APP == Calling GetDataAsync on SmokeDetectorActor:1...
== APP == Device 1 state: Location: First Floor, Status: Ready
== APP == Calling SetDataAsync on SmokeDetectorActor:2...
== APP == Got response: Success
== APP == Calling GetDataAsync on SmokeDetectorActor:2...
== APP == Device 2 state: Location: Second Floor, Status: Ready
== APP == Registering the IDs of both Devices...
== APP == Registered devices: 1, 2
== APP == Detecting smoke on Device 1...
== APP == Device 1 state: Location: First Floor, Status: Alarm
== APP == Device 2 state: Location: Second Floor, Status: Alarm
== APP == Sleeping for 16 seconds before checking status again to see reminders fire and clear alarms
== APP == Device 1 state: Location: First Floor, Status: Ready
== APP == Device 2 state: Location: Second Floor, Status: Ready
(선택) 4단계: Zipkin에서 확인하기
머신의 로컬 Dapr에 Zipkin을 구성해 뒀다면, Zipkin 웹 UI(보통 http://localhost:9411/zipkin/)에서 클라이언트와 actor의 상호작용을 볼 수 있어요.
무슨 일이 일어났나요?
클라이언트 앱을 실행했을 때 몇 가지 일이 벌어졌어요.
- 클라이언트 어플리케이션에 SmokeDetectorActor 두 개가 생성되고, 다음과 같이 객체 상태로 초기화됐어요.
ActorProxy.Create<ISmartDevice>(actorId, actorType)proxySmartDevice.SetDataAsync(data)
- 이 객체들은 재진입(re-entrant)이 가능하고 상태를 보유해요.
proxySmartDevice.GetDataAsync()로 확인할 수 있어요.
// Actor Ids and types
var deviceId1 = "1";
var deviceId2 = "2";
var smokeDetectorActorType = "SmokeDetectorActor";
var controllerActorType = "ControllerActor";
Console.WriteLine("Startup up...");
// An ActorId uniquely identifies the first actor instance for the first device
var deviceActorId1 = new ActorId(deviceId1);
// Create a new instance of the data class that will be stored in the first actor
var deviceData1 = new SmartDeviceData(){
Location = "First Floor",
Status = "Ready",
};
// Create the local proxy by using the same interface that the service implements.
var proxySmartDevice1 = ActorProxy.Create<ISmartDevice>(deviceActorId1, smokeDetectorActorType);
// Now you can use the actor interface to call the actor's methods.
Console.WriteLine($"Calling SetDataAsync on {smokeDetectorActorType}:{deviceActorId1}...");
var setDataResponse1 = await proxySmartDevice1.SetDataAsync(deviceData1);
Console.WriteLine($"Got response: {setDataResponse1}");
Console.WriteLine($"Calling GetDataAsync on {smokeDetectorActorType}:{deviceActorId1}...");
var storedDeviceData1 = await proxySmartDevice1.GetDataAsync();
Console.WriteLine($"Device 1 state: {storedDeviceData1}");
// Create a second actor for second device
var deviceActorId2 = new ActorId(deviceId2);
// Create a new instance of the data class that will be stored in the first actor
var deviceData2 = new SmartDeviceData(){
Location = "Second Floor",
Status = "Ready",
};
// Create the local proxy by using the same interface that the service implements.
var proxySmartDevice2 = ActorProxy.Create<ISmartDevice>(deviceActorId2, smokeDetectorActorType);
// Now you can use the actor interface to call the second actor's methods.
Console.WriteLine($"Calling SetDataAsync on {smokeDetectorActorType}:{deviceActorId2}...");
var setDataResponse2 = await proxySmartDevice2.SetDataAsync(deviceData2);
Console.WriteLine($"Got response: {setDataResponse2}");
Console.WriteLine($"Calling GetDataAsync on {smokeDetectorActorType}:{deviceActorId2}...");
var storedDeviceData2 = await proxySmartDevice2.GetDataAsync();
Console.WriteLine($"Device 2 state: {storedDeviceData2}");
- SmokeDetectorActor 1의 DetectSmokeAsync 메서드가 호출됐어요.
public async Task DetectSmokeAsync()
{
var controllerActorId = new ActorId("controller");
var controllerActorType = "ControllerActor";
var controllerProxy = ProxyFactory.CreateActorProxy<IController>(controllerActorId, controllerActorType);
await controllerProxy.TriggerAlarmForAllDetectors();
}
- ControllerActor의 TriggerAlarmForAllDetectors 메서드가 호출됐어요. ControllerActor는 연기가 감지되면 내부적으로 모든 알람을 트리거해요.
public async Task TriggerAlarmForAllDetectors()
{
var deviceIds = await ListRegisteredDeviceIdsAsync();
foreach (var deviceId in deviceIds)
{
var actorId = new ActorId(deviceId);
var proxySmartDevice = ProxyFactory.CreateActorProxy<ISmartDevice>(actorId, "SmokeDetectorActor");
await proxySmartDevice.SoundAlarm();
}
// Register a reminder to refresh and clear alarm state every 15 seconds
await this.RegisterReminderAsync("AlarmRefreshReminder", null, TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(15));
}
콘솔에 연기가 감지됐다는 메시지가 출력돼요.
// Smoke is detected on device 1 that triggers an alarm on all devices.
Console.WriteLine($"Detecting smoke on Device 1...");
proxySmartDevice1 = ActorProxy.Create<ISmartDevice>(deviceActorId1, smokeDetectorActorType);
await proxySmartDevice1.DetectSmokeAsync();
- SmokeDetectorActor 1과 2의 SoundAlarm 메서드가 호출됐어요.
storedDeviceData1 = await proxySmartDevice1.GetDataAsync();
Console.WriteLine($"Device 1 state: {storedDeviceData1}");
storedDeviceData2 = await proxySmartDevice2.GetDataAsync();
Console.WriteLine($"Device 2 state: {storedDeviceData2}");
- ControllerActor는 RegisterReminderAsync를 사용해 15초 후 ClearAlarm을 호출하는 영속 리마인더(durable reminder)도 만들어요.
// Register a reminder to refresh and clear alarm state every 15 seconds
await this.RegisterReminderAsync("AlarmRefreshReminder", null, TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(15));
샘플의 전체 맥락은 다음 코드를 참고해요.
- SmokeDetectorActor.cs: 스마트 디바이스 actor를 구현해요
- ControllerActor.cs: 모든 디바이스를 관리하는 컨트롤러 actor를 구현해요
- ISmartDevice: 각 SmokeDetectorActor의 메서드 정의와 공유 데이터 타입이에요
- IController: ControllerActor의 메서드 정의와 공유 데이터 타입이에요
Dapr Dev Dashboard로 actor 확인하기
서비스와 클라이언트 앱이 실행되는 동안 Dapr Dev Dashboard를 사용해 등록된 SmokeDetectorActor와 ControllerActor 타입과 활성 actor 인스턴스를 볼 수 있어요. Dashboard는 상태 저장소에 저장된 actor 상태도 보여주므로, 알람이 울리고 리마인더가 그 상태를 클리어할 때 각 디바이스의 상태가 어떻게 변하는지 따라갈 수 있어요.
의견을 들려주세요!
우린 Quickstart 예제를 계속 개선하고 있고 여러분의 피드백을 소중히 여겨요. 이 Quickstart가 도움이 됐나요? 개선할 제안이 있나요? Discord Server에 참여해서 의견을 공유해 주세요.
다음 단계
Actors 빌딩 블록에 대해 더 알아보기 Dapr tutorials 탐색하기 >>