本节我们将使用Step Function实现以下工作流:
传入一个Purchase Type事件,当它为PURCHASE时,调用purchase lambda处理;如果是REFUND,则调用refund lambda处理。

进入Lambda页面,创建purchase_function函数:

代码更新如下,并进行部署:
import json
import datetime
def lambda_handler(message, context):
print(message)
response = {}
response['TransactionType']=message['TransactionType']
response["TimeStamp"] = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")
response["Message"] = "Hello from lambda land inside the ProcessPurchase function!"
return response
再创建refund_function:

更新代码如下,进行部署:
import json
import datetime
def lambda_handler(message, context):
print(message)
response = {}
response['TransactionType']=message['TransactionType']
response["TimeStamp"] = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")
response["Message"] = "Hello from lambda land inside the RefundPruchase function!"
return response
将上面创建的两个Lambda的ARN复制下来,后面会使用到:

形如以下格式:
arn:aws:lambda:us-east-1:145197526627:function:refund_function
arn:aws:lambda:us-east-1:145197526627:function:purchase_function
进入Step Functions服务,点击Create state machine:

这里我们选择Write your workflow in code:

Step Functions的JSON定义如下,将两处Resource替换为上一步获取到的Lambda ARN:
{
"Comment": "Transaction Process State Machine",
"StartAt": "ProcessTransaction",
"States": {
"ProcessTransaction": {
"Type": "Choice",
"Choices": [
{
"Variable": "$.TransactionType",
"StringEquals": "PURCHASE",
"Next": "ProcessPurchase"
},
{
"Variable": "$.TransactionType",
"StringEquals": "REFUND",
"Next": "ProcessRefund"
}
]
},
"ProcessRefund": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:145197526627:function:refund_function",
"End": true
},
"ProcessPurchase": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:145197526627:function:purchase_function",
"End": true
}
}
}
更新State Machine的JSON定义后,Step Functions会实时渲染出对应的流程图:

进入下一步,为Step Function命名,其他选项保持默认:

下拉到底部,发现Step Functions智能地分析出了需要哪些权限(调用两个Lambda),并附加到Role中:

点击创建。创建完成后进行测试,点击Start execution:


测试Input如下:
{
"TransactionType": "PURCHASE"
}
点击执行。在页面中能看到实时执行的结果,当执行完成后,可查看每个阶段的输入和输出:

在ProcessPurchas阶段,返回了Lambda的执行结果
新建Refund测试:

将TransactionType更改为REFUND:

执行后,程序走的ProcessRefund分支,并能查看到对应Lambda的输出:
