能否通过AWS API Gateway同步调用AWS Step Functions?状态机仅支持异步任务吗?
嘿,这两个问题我刚好有实战经验,来给你详细解答:
API Gateway与Step Functions同步请求及状态机执行模式解析
1. 能不能通过API Gateway向Step Functions发起同步请求?
绝对可以!你只需要让API Gateway集成Step Functions的StartSyncExecution API就能实现同步调用。这种模式下,API Gateway会一直等待Step Functions状态机执行完毕,然后直接把执行结果返回给调用方,不用像异步那样还要额外调用DescribeExecution去轮询结果,非常适合短流程的场景。
给你个快速配置参考(基于你提供的异步配置修改):
ApiGatewayMethodStartSyncExecution: Type: 'AWS::ApiGateway::Method' Properties: # 记得补充HttpMethod、ResourceId、AuthorizationType等必要属性 Integration: Type: AWS Uri: arn:aws:apigateway:eu-north-1:states:action/StartSyncExecution RequestTemplates: application/json: !Sub - | { "stateMachineArn": "${StateMachineArn}", "input": "$input.json('$')" } - StateMachineArn: !Ref AStateMachine IntegrationResponses: - StatusCode: 200 ResponseTemplates: application/json: "$input.json('$')"
2. AWS状态机只能用来启动异步任务吗?
当然不是!Step Functions同时支持同步和异步两种执行模式,完全看你的业务需求来选:
- 异步执行:就像你给出的示例那样,适合运行时间较长(超过API Gateway默认29秒超时,哪怕调整上限到60秒还是不够的场景)的任务。调用
StartExecution启动状态机后,它会在后台运行,你需要通过DescribeExecution去查询执行状态和结果。 - 同步执行:适合短运行的任务(执行时间在API Gateway超时范围内),调用
StartSyncExecution后,请求会一直挂起直到状态机执行完成,直接拿到结果,省去了轮询的麻烦。
你提供的异步任务CloudFormation配置示例
ApiGatewayMethodStartExecution: Type: 'AWS::ApiGateway::Method' Properties: ... Integration: Type: AWS Uri: arn:aws:apigateway:eu-north-1:states:action/StartExecution RequestTemplates: application/json: !Sub - | .... - StateMachineArn: !Ref AStateMachine ApiGatewayMethodGetResult: Type: 'AWS::ApiGateway::Method' Properties: ... Integration: Type: AWS Uri: arn:aws:apigateway:eu-north-1:states:action/DescribeExecution RequestTemplates: application/json: !Sub - | .... - StateMachineArn: !Ref AStateMachine AStateMachine: Type: 'AWS::StepFunctions::StateMachine' ...
这个配置就是标准的异步模式:一个API负责启动状态机,另一个API负责查询执行结果,很适合长流程的后台任务。
内容的提问来源于stack exchange,提问作者Leonard Saers
相关产品推荐
相关产品推荐

