AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
用SDK于 Kotlin 的 Step Functions 示例
以下代码示例向您展示了如何使用带有 Step Functions 的 kotlin 来执行操作和实现常见场景。 AWS SDK
基础知识是向您展示如何在服务中执行基本操作的代码示例。
操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景的上下文查看操作。
每个示例都包含一个指向完整源代码的链接,您可以在其中找到有关如何在上下文中设置和运行代码的说明。
开始使用
以下代码示例展示了如何开始使用 Step Functions。
- SDK对于 Kotlin 来说
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 import aws.sdk.kotlin.services.sfn.SfnClient import aws.sdk.kotlin.services.sfn.model.ListStateMachinesRequest /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main() { println(DASHES) println("Welcome to the AWS Step Functions Hello example.") println("Lets list up to ten of your state machines:") println(DASHES) listMachines() } suspend fun listMachines() { SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.listStateMachines(ListStateMachinesRequest {}) response.stateMachines?.forEach { machine -> println("The name of the state machine is ${machine.name}") println("The ARN value is ${machine.stateMachineArn}") } } }
-
有关API详细信息,请参阅ListStateMachines
中的 Kotlin AWS SDK API 参考。
-
基础知识
以下代码示例展示了如何:
创建活动。
根据包含先前创建的活动作为步骤的 Amazon States Language 定义创建状态机。
运行状态机并使用用户输入响应活动。
运行完成后获取最终状态和输出,然后清理资源。
- SDK对于 Kotlin 来说
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 import aws.sdk.kotlin.services.iam.IamClient import aws.sdk.kotlin.services.iam.model.CreateRoleRequest import aws.sdk.kotlin.services.sfn.SfnClient import aws.sdk.kotlin.services.sfn.model.CreateActivityRequest import aws.sdk.kotlin.services.sfn.model.CreateStateMachineRequest import aws.sdk.kotlin.services.sfn.model.DeleteActivityRequest import aws.sdk.kotlin.services.sfn.model.DeleteStateMachineRequest import aws.sdk.kotlin.services.sfn.model.DescribeExecutionRequest import aws.sdk.kotlin.services.sfn.model.DescribeStateMachineRequest import aws.sdk.kotlin.services.sfn.model.GetActivityTaskRequest import aws.sdk.kotlin.services.sfn.model.ListActivitiesRequest import aws.sdk.kotlin.services.sfn.model.ListStateMachinesRequest import aws.sdk.kotlin.services.sfn.model.SendTaskSuccessRequest import aws.sdk.kotlin.services.sfn.model.StartExecutionRequest import aws.sdk.kotlin.services.sfn.model.StateMachineType import aws.sdk.kotlin.services.sfn.paginators.listActivitiesPaginated import aws.sdk.kotlin.services.sfn.paginators.listStateMachinesPaginated import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ObjectNode import kotlinx.coroutines.flow.transform import java.util.Scanner import java.util.UUID import kotlin.collections.ArrayList import kotlin.system.exitProcess /** To run this code example, place the chat_sfn_state_machine.json file into your project's resources folder. You can obtain the JSON file to create a state machine in the following GitHub location: https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/resources/sample_files Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html This Kotlin code example performs the following tasks: 1. List activities using a paginator. 2. List state machines using a paginator. 3. Creates an activity. 4. Creates a state machine. 5. Describes the state machine. 6. Starts execution of the state machine and interacts with it. 7. Describes the execution. 8. Deletes the activity. 9. Deletes the state machine. */ val DASHES: String = String(CharArray(80)).replace("\u0000", "-") suspend fun main(args: Array<String>) { val usage = """ Usage: <roleARN> <activityName> <stateMachineName> Where: roleName - The name of the IAM role to create for this state machine. activityName - The name of an activity to create. stateMachineName - The name of the state machine to create. """ if (args.size != 3) { println(usage) exitProcess(0) } val roleName = args[0] val activityName = args[1] val stateMachineName = args[2] val sc = Scanner(System.`in`) var action = false val polJSON = """{ "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "Service": "states.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }""" println(DASHES) println("Welcome to the AWS Step Functions example scenario.") println(DASHES) println(DASHES) println("1. List activities using a Paginator.") listActivitesPagnator() println(DASHES) println(DASHES) println("2. List state machines using a paginator.") listStatemachinesPagnator() println(DASHES) println(DASHES) println("3. Create a new activity.") val activityArn = createActivity(activityName) println("The ARN of the Activity is $activityArn") println(DASHES) // Get JSON to use for the state machine and place the activityArn value into it. val stream = GetStream() val jsonString = stream.getStream() // Modify the Resource node. val objectMapper = ObjectMapper() val root: JsonNode = objectMapper.readTree(jsonString) (root.path("States").path("GetInput") as ObjectNode).put("Resource", activityArn) // Convert the modified Java object back to a JSON string. val stateDefinition = objectMapper.writeValueAsString(root) println(stateDefinition) println(DASHES) println("4. Create a state machine.") val roleARN = createIAMRole(roleName, polJSON) val stateMachineArn = createMachine(roleARN, stateMachineName, stateDefinition) println("The ARN of the state machine is $stateMachineArn") println(DASHES) println(DASHES) println("5. Describe the state machine.") describeStateMachine(stateMachineArn) println("What should ChatSFN call you?") val userName = sc.nextLine() println("Hello $userName") println(DASHES) println(DASHES) // The JSON to pass to the StartExecution call. val executionJson = "{ \"name\" : \"$userName\" }" println(executionJson) println("6. Start execution of the state machine and interact with it.") val runArn = startWorkflow(stateMachineArn, executionJson) println("The ARN of the state machine execution is $runArn") var myList: List<String> while (!action) { myList = getActivityTask(activityArn) println("ChatSFN: " + myList[1]) println("$userName please specify a value.") val myAction = sc.nextLine() if (myAction.compareTo("done") == 0) { action = true } println("You have selected $myAction") val taskJson = "{ \"action\" : \"$myAction\" }" println(taskJson) sendTaskSuccess(myList[0], taskJson) } println(DASHES) println(DASHES) println("7. Describe the execution.") describeExe(runArn) println(DASHES) println(DASHES) println("8. Delete the activity.") deleteActivity(activityArn) println(DASHES) println(DASHES) println("9. Delete the state machines.") deleteMachine(stateMachineArn) println(DASHES) println(DASHES) println("The AWS Step Functions example scenario is complete.") println(DASHES) } suspend fun listStatemachinesPagnator() { val machineRequest = ListStateMachinesRequest { maxResults = 10 } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient .listStateMachinesPaginated(machineRequest) .transform { it.stateMachines?.forEach { obj -> emit(obj) } } .collect { obj -> println(" The state machine ARN is ${obj.stateMachineArn}") } } } suspend fun listActivitesPagnator() { val activitiesRequest = ListActivitiesRequest { maxResults = 10 } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient .listActivitiesPaginated(activitiesRequest) .transform { it.activities?.forEach { obj -> emit(obj) } } .collect { obj -> println(" The activity ARN is ${obj.activityArn}") } } } suspend fun deleteMachine(stateMachineArnVal: String?) { val deleteStateMachineRequest = DeleteStateMachineRequest { stateMachineArn = stateMachineArnVal } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.deleteStateMachine(deleteStateMachineRequest) println("$stateMachineArnVal was successfully deleted.") } } suspend fun deleteActivity(actArn: String?) { val activityRequest = DeleteActivityRequest { activityArn = actArn } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.deleteActivity(activityRequest) println("You have deleted $actArn") } } suspend fun describeExe(executionArnVal: String?) { val executionRequest = DescribeExecutionRequest { executionArn = executionArnVal } var status = "" var hasSucceeded = false while (!hasSucceeded) { SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.describeExecution(executionRequest) status = response.status.toString() if (status.compareTo("RUNNING") == 0) { println("The state machine is still running, let's wait for it to finish.") Thread.sleep(2000) } else if (status.compareTo("SUCCEEDED") == 0) { println("The Step Function workflow has succeeded") hasSucceeded = true } else { println("The Status is neither running or succeeded") } } } println("The Status is $status") } suspend fun sendTaskSuccess( token: String?, json: String?, ) { val successRequest = SendTaskSuccessRequest { taskToken = token output = json } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.sendTaskSuccess(successRequest) } } suspend fun getActivityTask(actArn: String?): List<String> { val myList: MutableList<String> = ArrayList() val getActivityTaskRequest = GetActivityTaskRequest { activityArn = actArn } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.getActivityTask(getActivityTaskRequest) myList.add(response.taskToken.toString()) myList.add(response.input.toString()) return myList } } suspend fun startWorkflow( stateMachineArnVal: String?, jsonEx: String?, ): String? { val uuid = UUID.randomUUID() val uuidValue = uuid.toString() val executionRequest = StartExecutionRequest { input = jsonEx stateMachineArn = stateMachineArnVal name = uuidValue } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.startExecution(executionRequest) return response.executionArn } } suspend fun describeStateMachine(stateMachineArnVal: String?) { val stateMachineRequest = DescribeStateMachineRequest { stateMachineArn = stateMachineArnVal } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.describeStateMachine(stateMachineRequest) println("The name of the State machine is ${response.name}") println("The status of the State machine is ${response.status}") println("The ARN value of the State machine is ${response.stateMachineArn}") println("The role ARN value is ${response.roleArn}") } } suspend fun createMachine( roleARNVal: String?, stateMachineName: String?, jsonVal: String?, ): String? { val machineRequest = CreateStateMachineRequest { definition = jsonVal name = stateMachineName roleArn = roleARNVal type = StateMachineType.Standard } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.createStateMachine(machineRequest) return response.stateMachineArn } } suspend fun createIAMRole( roleNameVal: String?, polJSON: String?, ): String? { val request = CreateRoleRequest { roleName = roleNameVal assumeRolePolicyDocument = polJSON description = "Created using the AWS SDK for Kotlin" } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.createRole(request) return response.role?.arn } } suspend fun createActivity(activityName: String): String? { val activityRequest = CreateActivityRequest { name = activityName } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.createActivity(activityRequest) return response.activityArn } }
操作
以下代码示例显示了如何使用CreateActivity
。
- SDK对于 Kotlin 来说
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 suspend fun createActivity(activityName: String): String? { val activityRequest = CreateActivityRequest { name = activityName } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.createActivity(activityRequest) return response.activityArn } }
-
有关API详细信息,请参阅CreateActivity
中的 Kotlin AWS SDK API 参考。
-
以下代码示例显示了如何使用CreateStateMachine
。
- SDK对于 Kotlin 来说
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 suspend fun createMachine( roleARNVal: String?, stateMachineName: String?, jsonVal: String?, ): String? { val machineRequest = CreateStateMachineRequest { definition = jsonVal name = stateMachineName roleArn = roleARNVal type = StateMachineType.Standard } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.createStateMachine(machineRequest) return response.stateMachineArn } }
-
有关API详细信息,请参阅CreateStateMachine
中的 Kotlin AWS SDK API 参考。
-
以下代码示例显示了如何使用DeleteActivity
。
- SDK对于 Kotlin 来说
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 suspend fun deleteActivity(actArn: String?) { val activityRequest = DeleteActivityRequest { activityArn = actArn } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.deleteActivity(activityRequest) println("You have deleted $actArn") } }
-
有关API详细信息,请参阅DeleteActivity
中的 Kotlin AWS SDK API 参考。
-
以下代码示例显示了如何使用DeleteStateMachine
。
- SDK对于 Kotlin 来说
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 suspend fun deleteMachine(stateMachineArnVal: String?) { val deleteStateMachineRequest = DeleteStateMachineRequest { stateMachineArn = stateMachineArnVal } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.deleteStateMachine(deleteStateMachineRequest) println("$stateMachineArnVal was successfully deleted.") } }
-
有关API详细信息,请参阅DeleteStateMachine
中的 Kotlin AWS SDK API 参考。
-
以下代码示例显示了如何使用DescribeExecution
。
- SDK对于 Kotlin 来说
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 suspend fun describeExe(executionArnVal: String?) { val executionRequest = DescribeExecutionRequest { executionArn = executionArnVal } var status = "" var hasSucceeded = false while (!hasSucceeded) { SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.describeExecution(executionRequest) status = response.status.toString() if (status.compareTo("RUNNING") == 0) { println("The state machine is still running, let's wait for it to finish.") Thread.sleep(2000) } else if (status.compareTo("SUCCEEDED") == 0) { println("The Step Function workflow has succeeded") hasSucceeded = true } else { println("The Status is neither running or succeeded") } } } println("The Status is $status") }
-
有关API详细信息,请参阅DescribeExecution
中的 Kotlin AWS SDK API 参考。
-
以下代码示例显示了如何使用DescribeStateMachine
。
- SDK对于 Kotlin 来说
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 suspend fun describeStateMachine(stateMachineArnVal: String?) { val stateMachineRequest = DescribeStateMachineRequest { stateMachineArn = stateMachineArnVal } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.describeStateMachine(stateMachineRequest) println("The name of the State machine is ${response.name}") println("The status of the State machine is ${response.status}") println("The ARN value of the State machine is ${response.stateMachineArn}") println("The role ARN value is ${response.roleArn}") } }
-
有关API详细信息,请参阅DescribeStateMachine
中的 Kotlin AWS SDK API 参考。
-
以下代码示例显示了如何使用GetActivityTask
。
- SDK对于 Kotlin 来说
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 suspend fun getActivityTask(actArn: String?): List<String> { val myList: MutableList<String> = ArrayList() val getActivityTaskRequest = GetActivityTaskRequest { activityArn = actArn } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.getActivityTask(getActivityTaskRequest) myList.add(response.taskToken.toString()) myList.add(response.input.toString()) return myList } }
-
有关API详细信息,请参阅GetActivityTask
中的 Kotlin AWS SDK API 参考。
-
以下代码示例显示了如何使用ListActivities
。
- SDK对于 Kotlin 来说
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 suspend fun listAllActivites() { val activitiesRequest = ListActivitiesRequest { maxResults = 10 } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.listActivities(activitiesRequest) response.activities?.forEach { item -> println("The activity ARN is ${item.activityArn}") println("The activity name is ${item.name}") } } }
-
有关API详细信息,请参阅ListActivities
中的 Kotlin AWS SDK API 参考。
-
以下代码示例显示了如何使用ListExecutions
。
- SDK对于 Kotlin 来说
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 suspend fun getExeHistory(exeARN: String?) { val historyRequest = GetExecutionHistoryRequest { executionArn = exeARN maxResults = 10 } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.getExecutionHistory(historyRequest) response.events?.forEach { event -> println("The event type is ${event.type}") } } }
-
有关API详细信息,请参阅ListExecutions
中的 Kotlin AWS SDK API 参考。
-
以下代码示例显示了如何使用ListStateMachines
。
- SDK对于 Kotlin 来说
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 import aws.sdk.kotlin.services.sfn.SfnClient import aws.sdk.kotlin.services.sfn.model.ListStateMachinesRequest /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main() { println(DASHES) println("Welcome to the AWS Step Functions Hello example.") println("Lets list up to ten of your state machines:") println(DASHES) listMachines() } suspend fun listMachines() { SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.listStateMachines(ListStateMachinesRequest {}) response.stateMachines?.forEach { machine -> println("The name of the state machine is ${machine.name}") println("The ARN value is ${machine.stateMachineArn}") } } }
-
有关API详细信息,请参阅ListStateMachines
中的 Kotlin AWS SDK API 参考。
-
以下代码示例显示了如何使用SendTaskSuccess
。
- SDK对于 Kotlin 来说
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 suspend fun sendTaskSuccess( token: String?, json: String?, ) { val successRequest = SendTaskSuccessRequest { taskToken = token output = json } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.sendTaskSuccess(successRequest) } }
-
有关API详细信息,请参阅SendTaskSuccess
中的 Kotlin AWS SDK API 参考。
-
以下代码示例显示了如何使用StartExecution
。
- SDK对于 Kotlin 来说
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 suspend fun startWorkflow( stateMachineArnVal: String?, jsonEx: String?, ): String? { val uuid = UUID.randomUUID() val uuidValue = uuid.toString() val executionRequest = StartExecutionRequest { input = jsonEx stateMachineArn = stateMachineArnVal name = uuidValue } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.startExecution(executionRequest) return response.executionArn } }
-
有关API详细信息,请参阅StartExecution
中的 Kotlin AWS SDK API 参考。
-