How to: Author and manage Dapr Workflow in the Java SDK

How to get up and running with workflows using the Dapr Java SDK

Note

Dapr Workflow is currently in beta. See known limitations for 1.13.0.

Let’s create a Dapr workflow and invoke it using the console. With the provided workflow example, you will:

This example uses the default configuration from dapr init in self-hosted mode.

Prerequisites

Set up the environment

Clone the Java SDK repo and navigate into it.

  1. git clone https://github.com/dapr/java-sdk.git
  2. cd java-sdk

Run the following command to install the requirements for running this workflow sample with the Dapr Java SDK.

  1. mvn clean install

From the Java SDK root directory, navigate to the Dapr Workflow example.

  1. cd examples

Run the DemoWorkflowWorker

The DemoWorkflowWorker class registers an implementation of DemoWorkflow in Dapr’s workflow runtime engine. In the DemoWorkflowWorker.java file, you can find the DemoWorkflowWorker class and the main method:

  1. public class DemoWorkflowWorker {
  2. public static void main(String[] args) throws Exception {
  3. // Register the Workflow with the runtime.
  4. WorkflowRuntime.getInstance().registerWorkflow(DemoWorkflow.class);
  5. System.out.println("Start workflow runtime");
  6. WorkflowRuntime.getInstance().startAndBlock();
  7. System.exit(0);
  8. }
  9. }

In the code above:

  • WorkflowRuntime.getInstance().registerWorkflow() registers DemoWorkflow as a workflow in the Dapr Workflow runtime.
  • WorkflowRuntime.getInstance().start() builds and starts the engine within the Dapr Workflow runtime.

In the terminal, execute the following command to kick off the DemoWorkflowWorker:

  1. dapr run --app-id demoworkflowworker --resources-path ./components/workflows --dapr-grpc-port 50001 -- java -jar target/dapr-java-sdk-examples-exec.jar io.dapr.examples.workflows.DemoWorkflowWorker

Expected output

  1. You're up and running! Both Dapr and your app logs will appear here.
  2. ...
  3. == APP == Start workflow runtime
  4. == APP == Sep 13, 2023 9:02:03 AM com.microsoft.durabletask.DurableTaskGrpcWorker startAndBlock
  5. == APP == INFO: Durable Task worker is connecting to sidecar at 127.0.0.1:50001.

Run the `DemoWorkflowClient

The DemoWorkflowClient starts instances of workflows that have been registered with Dapr.

  1. public class DemoWorkflowClient {
  2. // ...
  3. public static void main(String[] args) throws InterruptedException {
  4. DaprWorkflowClient client = new DaprWorkflowClient();
  5. try (client) {
  6. String separatorStr = "*******";
  7. System.out.println(separatorStr);
  8. String instanceId = client.scheduleNewWorkflow(DemoWorkflow.class, "input data");
  9. System.out.printf("Started new workflow instance with random ID: %s%n", instanceId);
  10. System.out.println(separatorStr);
  11. System.out.println("**GetInstanceMetadata:Running Workflow**");
  12. WorkflowInstanceStatus workflowMetadata = client.getInstanceState(instanceId, true);
  13. System.out.printf("Result: %s%n", workflowMetadata);
  14. System.out.println(separatorStr);
  15. System.out.println("**WaitForInstanceStart**");
  16. try {
  17. WorkflowInstanceStatus waitForInstanceStartResult =
  18. client.waitForInstanceStart(instanceId, Duration.ofSeconds(60), true);
  19. System.out.printf("Result: %s%n", waitForInstanceStartResult);
  20. } catch (TimeoutException ex) {
  21. System.out.printf("waitForInstanceStart has an exception:%s%n", ex);
  22. }
  23. System.out.println(separatorStr);
  24. System.out.println("**SendExternalMessage**");
  25. client.raiseEvent(instanceId, "TestEvent", "TestEventPayload");
  26. System.out.println(separatorStr);
  27. System.out.println("** Registering parallel Events to be captured by allOf(t1,t2,t3) **");
  28. client.raiseEvent(instanceId, "event1", "TestEvent 1 Payload");
  29. client.raiseEvent(instanceId, "event2", "TestEvent 2 Payload");
  30. client.raiseEvent(instanceId, "event3", "TestEvent 3 Payload");
  31. System.out.printf("Events raised for workflow with instanceId: %s\n", instanceId);
  32. System.out.println(separatorStr);
  33. System.out.println("** Registering Event to be captured by anyOf(t1,t2,t3) **");
  34. client.raiseEvent(instanceId, "e2", "event 2 Payload");
  35. System.out.printf("Event raised for workflow with instanceId: %s\n", instanceId);
  36. System.out.println(separatorStr);
  37. System.out.println("**WaitForInstanceCompletion**");
  38. try {
  39. WorkflowInstanceStatus waitForInstanceCompletionResult =
  40. client.waitForInstanceCompletion(instanceId, Duration.ofSeconds(60), true);
  41. System.out.printf("Result: %s%n", waitForInstanceCompletionResult);
  42. } catch (TimeoutException ex) {
  43. System.out.printf("waitForInstanceCompletion has an exception:%s%n", ex);
  44. }
  45. System.out.println(separatorStr);
  46. System.out.println("**purgeInstance**");
  47. boolean purgeResult = client.purgeInstance(instanceId);
  48. System.out.printf("purgeResult: %s%n", purgeResult);
  49. System.out.println(separatorStr);
  50. System.out.println("**raiseEvent**");
  51. String eventInstanceId = client.scheduleNewWorkflow(DemoWorkflow.class);
  52. System.out.printf("Started new workflow instance with random ID: %s%n", eventInstanceId);
  53. client.raiseEvent(eventInstanceId, "TestException", null);
  54. System.out.printf("Event raised for workflow with instanceId: %s\n", eventInstanceId);
  55. System.out.println(separatorStr);
  56. String instanceToTerminateId = "terminateMe";
  57. client.scheduleNewWorkflow(DemoWorkflow.class, null, instanceToTerminateId);
  58. System.out.printf("Started new workflow instance with specified ID: %s%n", instanceToTerminateId);
  59. TimeUnit.SECONDS.sleep(5);
  60. System.out.println("Terminate this workflow instance manually before the timeout is reached");
  61. client.terminateWorkflow(instanceToTerminateId, null);
  62. System.out.println(separatorStr);
  63. String restartingInstanceId = "restarting";
  64. client.scheduleNewWorkflow(DemoWorkflow.class, null, restartingInstanceId);
  65. System.out.printf("Started new workflow instance with ID: %s%n", restartingInstanceId);
  66. System.out.println("Sleeping 30 seconds to restart the workflow");
  67. TimeUnit.SECONDS.sleep(30);
  68. System.out.println("**SendExternalMessage: RestartEvent**");
  69. client.raiseEvent(restartingInstanceId, "RestartEvent", "RestartEventPayload");
  70. System.out.println("Sleeping 30 seconds to terminate the eternal workflow");
  71. TimeUnit.SECONDS.sleep(30);
  72. client.terminateWorkflow(restartingInstanceId, null);
  73. }
  74. System.out.println("Exiting DemoWorkflowClient.");
  75. System.exit(0);
  76. }
  77. }

In a second terminal window, start the workflow by running the following command:

  1. java -jar target/dapr-java-sdk-examples-exec.jar io.dapr.examples.workflows.DemoWorkflowClient

Expected output

  1. *******
  2. Started new workflow instance with random ID: 0b4cc0d5-413a-4c1c-816a-a71fa24740d4
  3. *******
  4. **GetInstanceMetadata:Running Workflow**
  5. Result: [Name: 'io.dapr.examples.workflows.DemoWorkflow', ID: '0b4cc0d5-413a-4c1c-816a-a71fa24740d4', RuntimeStatus: RUNNING, CreatedAt: 2023-09-13T13:02:30.547Z, LastUpdatedAt: 2023-09-13T13:02:30.699Z, Input: '"input data"', Output: '']
  6. *******
  7. **WaitForInstanceStart**
  8. Result: [Name: 'io.dapr.examples.workflows.DemoWorkflow', ID: '0b4cc0d5-413a-4c1c-816a-a71fa24740d4', RuntimeStatus: RUNNING, CreatedAt: 2023-09-13T13:02:30.547Z, LastUpdatedAt: 2023-09-13T13:02:30.699Z, Input: '"input data"', Output: '']
  9. *******
  10. **SendExternalMessage**
  11. *******
  12. ** Registering parallel Events to be captured by allOf(t1,t2,t3) **
  13. Events raised for workflow with instanceId: 0b4cc0d5-413a-4c1c-816a-a71fa24740d4
  14. *******
  15. ** Registering Event to be captured by anyOf(t1,t2,t3) **
  16. Event raised for workflow with instanceId: 0b4cc0d5-413a-4c1c-816a-a71fa24740d4
  17. *******
  18. **WaitForInstanceCompletion**
  19. Result: [Name: 'io.dapr.examples.workflows.DemoWorkflow', ID: '0b4cc0d5-413a-4c1c-816a-a71fa24740d4', RuntimeStatus: FAILED, CreatedAt: 2023-09-13T13:02:30.547Z, LastUpdatedAt: 2023-09-13T13:02:55.054Z, Input: '"input data"', Output: '']
  20. *******
  21. **purgeInstance**
  22. purgeResult: true
  23. *******
  24. **raiseEvent**
  25. Started new workflow instance with random ID: 7707d141-ebd0-4e54-816e-703cb7a52747
  26. Event raised for workflow with instanceId: 7707d141-ebd0-4e54-816e-703cb7a52747
  27. *******
  28. Started new workflow instance with specified ID: terminateMe
  29. Terminate this workflow instance manually before the timeout is reached
  30. *******
  31. Started new workflow instance with ID: restarting
  32. Sleeping 30 seconds to restart the workflow
  33. **SendExternalMessage: RestartEvent**
  34. Sleeping 30 seconds to terminate the eternal workflow
  35. Exiting DemoWorkflowClient.

What happened?

  1. When you ran dapr run, the workflow worker registered the workflow (DemoWorkflow) and its actvities to the Dapr Workflow engine.
  2. When you ran java, the workflow client started the workflow instance with the following activities. You can follow along with the output in the terminal where you ran dapr run.
    1. The workflow is started, raises three parallel tasks, and waits for them to complete.
    2. The workflow client calls the activity and sends the “Hello Activity” message to the console.
    3. The workflow times out and is purged.
    4. The workflow client starts a new workflow instance with a random ID, uses another workflow instance called terminateMe to terminate it, and restarts it with the workflow called restarting.
    5. The worfklow client is then exited.

Next steps