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

Java SDK에서 Dapr Workflow를 만들고 관리하는 방법

원문 보기 위키 갱신

Dapr Java SDK를 사용해서 워크플로를 시작하고 실행해봐요. 이 예제에서는 콘솔을 통해 Dapr 워크플로를 만들고 호출해볼 거예요. 제공된 워크플로 예제를 통해 여러분은:

  • Java 워크플로 워커를 사용해서 워크플로 인스턴스를 실행해요
  • Java 워크플로 클라이언트와 API 호출을 사용해서 워크플로 인스턴스를 시작하고 종료해요

이 예제는 self-hosted 모드의 dapr init 기본 구성을 사용해요.

출처: Dapr 문서

본문

사전 준비사항 (Prerequisites)

  • Dapr CLI와 초기화된 환경.

  • Java JDK 11 이상: Oracle JDK, 또는

  • OpenJDK

  • Apache Maven 3.x 버전.

  • Docker Desktop

  • 최신 proto 바인딩을 사용하고 있는지 확인해요

환경 설정하기

Java SDK 레포를 클론하고 해당 디렉터리로 이동해요.

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

Dapr Java SDK로 이 워크플로 예제를 실행하는 데 필요한 요구사항을 설치하려면 다음 명령을 실행해요.

mvn clean install

Java SDK 루트 디렉터리에서 Dapr 워크플로 예제로 이동해요.

cd examples

DemoWorkflowWorker 실행하기

DemoWorkflowWorker 클래스는 DemoWorkflow의 구현을 Dapr의 워크플로 런타임 엔진에 등록해요. DemoWorkflowWorker.java 파일에서 DemoWorkflowWorker 클래스와 main 메서드를 찾을 수 있어요:

public class DemoWorkflowWorker {

public static void main(String[] args) throws Exception {
// Register the Workflow with the runtime.
WorkflowRuntime.getInstance().registerWorkflow(DemoWorkflow.class);
System.out.println("Start workflow runtime");
WorkflowRuntime.getInstance().startAndBlock();
System.exit(0);
}
}

위 코드에서:

  • WorkflowRuntime.getInstance().registerWorkflow()는 DemoWorkflow를 Dapr 워크플로 런타임에 워크플로로 등록해요.
  • WorkflowRuntime.getInstance().start()는 Dapr 워크플로 런타임 내부에서 엔진을 빌드하고 시작해요.

터미널에서 다음 명령을 실행해서 DemoWorkflowWorker를 시작해요:

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)

You're up and running! Both Dapr and your app logs will appear here.

...

== APP == Start workflow runtime
== APP == Sep 13, 2023 9:02:03 AM com.microsoft.durabletask.DurableTaskGrpcWorker startAndBlock
== APP == INFO: Durable Task worker is connecting to sidecar at 127.0.0.1:50001.

DemoWorkflowClient 실행하기

DemoWorkflowClient는 Dapr에 등록된 워크플로의 인스턴스를 시작해요.

public class DemoWorkflowClient {

// ...
public static void main(String[] args) throws InterruptedException {
DaprWorkflowClient client = new DaprWorkflowClient();

try (client) {
String separatorStr = "*******";
System.out.println(separatorStr);
String instanceId = client.scheduleNewWorkflow(DemoWorkflow.class, "input data");
System.out.printf("Started new workflow instance with random ID: %s%n", instanceId);

System.out.println(separatorStr);
System.out.println("**GetInstanceMetadata:Running Workflow**");
WorkflowState workflowMetadata = client.getWorkflowState(instanceId, true);
System.out.printf("Result: %s%n", workflowMetadata);

System.out.println(separatorStr);
System.out.println("**WaitForWorkflowStart**");
try {
WorkflowState waitForWorkflowStartResult =
client.waitForWorkflowStart(instanceId, Duration.ofSeconds(60), true);
System.out.printf("Result: %s%n", waitForWorkflowStartResult);
} catch (TimeoutException ex) {
System.out.printf("waitForWorkflowStart has an exception:%s%n", ex);
}

System.out.println(separatorStr);
System.out.println("**SendExternalMessage**");
client.raiseEvent(instanceId, "TestEvent", "TestEventPayload");

System.out.println(separatorStr);
System.out.println("** Registering parallel Events to be captured by allOf(t1,t2,t3) **");
client.raiseEvent(instanceId, "event1", "TestEvent 1 Payload");
client.raiseEvent(instanceId, "event2", "TestEvent 2 Payload");
client.raiseEvent(instanceId, "event3", "TestEvent 3 Payload");
System.out.printf("Events raised for workflow with instanceId: %s\n", instanceId);

System.out.println(separatorStr);
System.out.println("** Registering Event to be captured by anyOf(t1,t2,t3) **");
client.raiseEvent(instanceId, "e2", "event 2 Payload");
System.out.printf("Event raised for workflow with instanceId: %s\n", instanceId);

System.out.println(separatorStr);
System.out.println("**waitForWorkflowCompletion**");
try {
WorkflowState waitForWorkflowCompletionResult =
client.waitForWorkflowCompletion(instanceId, Duration.ofSeconds(60), true);
System.out.printf("Result: %s%n", waitForWorkflowCompletionResult);
} catch (TimeoutException ex) {
System.out.printf("waitForWorkflowCompletion has an exception:%s%n", ex);
}

System.out.println(separatorStr);
System.out.println("**purgeWorkflow**");
boolean purgeResult = client.purgeWorkflow(instanceId);
System.out.printf("purgeResult: %s%n", purgeResult);

System.out.println(separatorStr);
System.out.println("**raiseEvent**");

String eventInstanceId = client.scheduleNewWorkflow(DemoWorkflow.class);
System.out.printf("Started new workflow instance with random ID: %s%n", eventInstanceId);
client.raiseEvent(eventInstanceId, "TestException", null);
System.out.printf("Event raised for workflow with instanceId: %s\n", eventInstanceId);

System.out.println(separatorStr);
String instanceToTerminateId = "terminateMe";
client.scheduleNewWorkflow(DemoWorkflow.class, null, instanceToTerminateId);
System.out.printf("Started new workflow instance with specified ID: %s%n", instanceToTerminateId);

TimeUnit.SECONDS.sleep(5);
System.out.println("Terminate this workflow instance manually before the timeout is reached");
client.terminateWorkflow(instanceToTerminateId, null);
System.out.println(separatorStr);

String restartingInstanceId = "restarting";
client.scheduleNewWorkflow(DemoWorkflow.class, null, restartingInstanceId);
System.out.printf("Started new workflow instance with ID: %s%n", restartingInstanceId);
System.out.println("Sleeping 30 seconds to restart the workflow");
TimeUnit.SECONDS.sleep(30);

System.out.println("**SendExternalMessage: RestartEvent**");
client.raiseEvent(restartingInstanceId, "RestartEvent", "RestartEventPayload");

System.out.println("Sleeping 30 seconds to terminate the eternal workflow");
TimeUnit.SECONDS.sleep(30);
client.terminateWorkflow(restartingInstanceId, null);
}

System.out.println("Exiting DemoWorkflowClient.");
System.exit(0);
}
}

두 번째 터미널 창에서 다음 명령을 실행해서 워크플로를 시작해요:

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

예상 출력 (Expected output)

*******
Started new workflow instance with random ID: 0b4cc0d5-413a-4c1c-816a-a71fa24740d4
*******
**GetInstanceMetadata:Running Workflow**
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: '']
*******
**WaitForWorkflowStart**
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: '']
*******
**SendExternalMessage**
*******
** Registering parallel Events to be captured by allOf(t1,t2,t3) **
Events raised for workflow with instanceId: 0b4cc0d5-413a-4c1c-816a-a71fa24740d4
*******
** Registering Event to be captured by anyOf(t1,t2,t3) **
Event raised for workflow with instanceId: 0b4cc0d5-413a-4c1c-816a-a71fa24740d4
*******
**WaitForWorkflowCompletion**
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: '']
*******
**purgeWorkflow**
purgeResult: true
*******
**raiseEvent**
Started new workflow instance with random ID: 7707d141-ebd0-4e54-816e-703cb7a52747
Event raised for workflow with instanceId: 7707d141-ebd0-4e54-816e-703cb7a52747
*******
Started new workflow instance with specified ID: terminateMe
Terminate this workflow instance manually before the timeout is reached
*******
Started new workflow instance with ID: restarting
Sleeping 30 seconds to restart the workflow
**SendExternalMessage: RestartEvent**
Sleeping 30 seconds to terminate the eternal workflow
Exiting DemoWorkflowClient.

어떤 일이 일어났나요? (What happened?)

  • dapr run을 실행하면 워크플로 워커가 워크플로(DemoWorkflow)와 그 활동(activity)들을 Dapr 워크플로 엔진에 등록해요.
  • java를 실행하면 워크플로 클라이언트가 다음 활동들을 사용해서 워크플로 인스턴스를 시작해요. dapr run을 실행한 터미널에서 출력을 따라가면서 확인할 수 있어요. 워크플로가 시작되고, 세 개의 병렬 작업을 실행한 다음 그것들이 완료될 때까지 기다려요.
  • 워크플로 클라이언트가 활동을 호출하고 "Hello Activity" 메시지를 콘솔로 보내요.
  • 워크플로가 타임아웃되어 제거(purge)돼요.
  • 워크플로 클라이언트가 무작위 ID로 새 워크플로 인스턴스를 시작하고, terminateMe라는 다른 워크플로 인스턴스를 사용해서 종료한 다음, restarting이라는 워크플로로 다시 시작해요.
  • 그러고 나서 워크플로 클라이언트가 종료돼요.

다음 단계 (Next steps)

  • Dapr 워크플로에 대해 더 알아보기
  • 워크플로 API 레퍼런스

고급 기능 (Advanced features)

Task Execution Keys

작업 실행 키(task execution key)는 durabletask-java 라이브러리가 생성하는 고유 식별자예요. 이 키는 WorkflowActivityContext에 저장되며 워크플로 활동의 실행을 추적하고 관리하는 데 사용할 수 있어요. 특히 다음 용도에 유용해요:

  • 멱등성(Idempotency): 같은 작업에 대해 활동이 여러 번 실행되지 않도록 보장해요
  • 상태 관리(State Management): 활동 실행의 상태를 추적해요
  • 오류 처리(Error Handling): 재시도와 실패를 통제된 방식으로 관리해요

워크플로 활동에서 작업 실행 키를 사용하는 예시는 다음과 같아요:

public class TaskExecutionKeyActivity implements WorkflowActivity {
@Override
public Object run(WorkflowActivityContext ctx) {
// Get the task execution key for this activity
String taskExecutionKey = ctx.getTaskExecutionKey();

// Use the key to implement idempotency or state management
// For example, check if this task has already been executed
if (isTaskAlreadyExecuted(taskExecutionKey)) {
return getPreviousResult(taskExecutionKey);
}

// Execute the activity logic
Object result = executeActivityLogic();

// Store the result with the task execution key
storeResult(taskExecutionKey, result);

return result;
}
}

더 알아보기 (Learn more)