Quickstart: Actors

Get started with Dapr’s Actors building block

Let’s take a look at Dapr’s Actors building block. In this Quickstart, you will run a smart device microservice and a simple console client to demonstrate the stateful object patterns in Dapr Actors.

Currently, you can experience this actors quickstart using the .NET SDK.

As a quick overview of the .NET actors quickstart:

  1. Using a SmartDevice.Service microservice, you host:
    • Two SmartDectectorActor smoke alarm objects
    • A ControllerActor object that commands and controls the smart devices
  2. Using a SmartDevice.Client console app, the client app interacts with each actor, or the controller, to perform actions in aggregate.
  3. The SmartDevice.Interfaces contains the shared interfaces and data types used by both the service and client apps.

Actors - 图1

Pre-requisites

For this example, you will need:

Step 1: Set up the environment

Clone the sample provided in the Quickstarts repo.

  1. git clone https://github.com/dapr/quickstarts.git

Step 2: Run the service app

In a new terminal window, navigate to the actors/csharp/sdk/service directory and restore dependencies:

  1. cd actors/csharp/sdk/service
  2. dotnet build

Run the SmartDevice.Service, which will start service itself and the Dapr sidecar:

  1. dapr run --app-id actorservice --app-port 5001 --dapr-http-port 3500 --resources-path ../../../resources -- dotnet run --urls=http://localhost:5001/

Expected output:

  1. == APP == info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
  2. == APP == Request starting HTTP/1.1 GET http://127.0.0.1:5001/healthz - -
  3. == APP == info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
  4. == APP == Executing endpoint 'Dapr Actors Health Check'
  5. == APP == info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
  6. == APP == Executed endpoint 'Dapr Actors Health Check'
  7. == APP == info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
  8. == APP == Request finished HTTP/1.1 GET http://127.0.0.1:5001/healthz - - - 200 - text/plain 5.2599ms

Step 3: Run the client app

In a new terminal instance, navigate to the actors/csharp/sdk/client directory and install the dependencies:

  1. cd ./actors/csharp/sdk/client
  2. dotnet build

Run the SmartDevice.Client app:

  1. dapr run --app-id actorclient -- dotnet run

Expected output:

  1. == APP == Startup up...
  2. == APP == Calling SetDataAsync on SmokeDetectorActor:1...
  3. == APP == Got response: Success
  4. == APP == Calling GetDataAsync on SmokeDetectorActor:1...
  5. == APP == Device 1 state: Location: First Floor, Status: Ready
  6. == APP == Calling SetDataAsync on SmokeDetectorActor:2...
  7. == APP == Got response: Success
  8. == APP == Calling GetDataAsync on SmokeDetectorActor:2...
  9. == APP == Device 2 state: Location: Second Floor, Status: Ready
  10. == APP == Registering the IDs of both Devices...
  11. == APP == Registered devices: 1, 2
  12. == APP == Detecting smoke on Device 1...
  13. == APP == Device 1 state: Location: First Floor, Status: Alarm
  14. == APP == Device 2 state: Location: Second Floor, Status: Alarm
  15. == APP == Sleeping for 16 seconds before checking status again to see reminders fire and clear alarms
  16. == APP == Device 1 state: Location: First Floor, Status: Ready
  17. == APP == Device 2 state: Location: Second Floor, Status: Ready

(Optional) Step 4: View in Zipkin

If you have Zipkin configured for Dapr locally on your machine, you can view the actor’s interaction with the client in the Zipkin web UI (typically at http://localhost:9411/zipkin/).

Actors - 图2

What happened?

When you ran the client app, a few things happened:

  1. Two SmartDetectorActor actors were created in the client application and initialized with object state with:

    • ActorProxy.Create<ISmartDevice>(actorId, actorType)
    • proxySmartDevice.SetDataAsync(data)

    These objects are re-entrant and hold the state, as shown by proxySmartDevice.GetDataAsync().

    1. // Actor Ids and types
    2. var deviceId1 = "1";
    3. var deviceId2 = "2";
    4. var smokeDetectorActorType = "SmokeDetectorActor";
    5. var controllerActorType = "ControllerActor";
    6. Console.WriteLine("Startup up...");
    7. // An ActorId uniquely identifies the first actor instance for the first device
    8. var deviceActorId1 = new ActorId(deviceId1);
    9. // Create a new instance of the data class that will be stored in the first actor
    10. var deviceData1 = new SmartDeviceData(){
    11. Location = "First Floor",
    12. Status = "Ready",
    13. };
    14. // Create the local proxy by using the same interface that the service implements.
    15. var proxySmartDevice1 = ActorProxy.Create<ISmartDevice>(deviceActorId1, smokeDetectorActorType);
    16. // Now you can use the actor interface to call the actor's methods.
    17. Console.WriteLine($"Calling SetDataAsync on {smokeDetectorActorType}:{deviceActorId1}...");
    18. var setDataResponse1 = await proxySmartDevice1.SetDataAsync(deviceData1);
    19. Console.WriteLine($"Got response: {setDataResponse1}");
    20. Console.WriteLine($"Calling GetDataAsync on {smokeDetectorActorType}:{deviceActorId1}...");
    21. var storedDeviceData1 = await proxySmartDevice1.GetDataAsync();
    22. Console.WriteLine($"Device 1 state: {storedDeviceData1}");
    23. // Create a second actor for second device
    24. var deviceActorId2 = new ActorId(deviceId2);
    25. // Create a new instance of the data class that will be stored in the first actor
    26. var deviceData2 = new SmartDeviceData(){
    27. Location = "Second Floor",
    28. Status = "Ready",
    29. };
    30. // Create the local proxy by using the same interface that the service implements.
    31. var proxySmartDevice2 = ActorProxy.Create<ISmartDevice>(deviceActorId2, smokeDetectorActorType);
    32. // Now you can use the actor interface to call the second actor's methods.
    33. Console.WriteLine($"Calling SetDataAsync on {smokeDetectorActorType}:{deviceActorId2}...");
    34. var setDataResponse2 = await proxySmartDevice2.SetDataAsync(deviceData2);
    35. Console.WriteLine($"Got response: {setDataResponse2}");
    36. Console.WriteLine($"Calling GetDataAsync on {smokeDetectorActorType}:{deviceActorId2}...");
    37. var storedDeviceData2 = await proxySmartDevice2.GetDataAsync();
    38. Console.WriteLine($"Device 2 state: {storedDeviceData2}");
  2. The DetectSmokeAsync method of SmartDetectorActor 1 is called.

    1. public async Task DetectSmokeAsync()
    2. {
    3. var controllerActorId = new ActorId("controller");
    4. var controllerActorType = "ControllerActor";
    5. var controllerProxy = ProxyFactory.CreateActorProxy<IController>(controllerActorId, controllerActorType);
    6. await controllerProxy.TriggerAlarmForAllDetectors();
    7. }
  3. The TriggerAlarmForAllDetectors method of ControllerActor is called. The ControllerActor internally triggers all alarms when smoke is detected

    1. public async Task TriggerAlarmForAllDetectors()
    2. {
    3. var deviceIds = await ListRegisteredDeviceIdsAsync();
    4. foreach (var deviceId in deviceIds)
    5. {
    6. var actorId = new ActorId(deviceId);
    7. var proxySmartDevice = ProxyFactory.CreateActorProxy<ISmartDevice>(actorId, "SmokeDetectorActor");
    8. await proxySmartDevice.SoundAlarm();
    9. }
    10. // Register a reminder to refresh and clear alarm state every 15 seconds
    11. await this.RegisterReminderAsync("AlarmRefreshReminder", null, TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(15));
    12. }

    The console prints a message indicating that smoke has been detected.

    1. // Smoke is detected on device 1 that triggers an alarm on all devices.
    2. Console.WriteLine($"Detecting smoke on Device 1...");
    3. proxySmartDevice1 = ActorProxy.Create<ISmartDevice>(deviceActorId1, smokeDetectorActorType);
    4. await proxySmartDevice1.DetectSmokeAsync();
  4. The SoundAlarm methods of SmartDetectorActor 1 and 2 are called.

    1. storedDeviceData1 = await proxySmartDevice1.GetDataAsync();
    2. Console.WriteLine($"Device 1 state: {storedDeviceData1}");
    3. storedDeviceData2 = await proxySmartDevice2.GetDataAsync();
    4. Console.WriteLine($"Device 2 state: {storedDeviceData2}");
  5. The ControllerActor also creates a durable reminder to call ClearAlarm after 15 seconds using RegisterReminderAsync.

    1. // Register a reminder to refresh and clear alarm state every 15 seconds
    2. await this.RegisterReminderAsync("AlarmRefreshReminder", null, TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(15));

For full context of the sample, take a look at the following code:

Tell us what you think!

We’re continuously working to improve our Quickstart examples and value your feedback. Did you find this Quickstart helpful? Do you have suggestions for improvement?

Join the discussion in our discord channel.

Next steps

Learn more about the Actor building block

Explore Dapr tutorials >>

Last modified June 19, 2023: Merge pull request #3565 from dapr/aacrawfi/skip-secrets-close (b1763bf)