aws(学习笔记第二十四课)
- 使用
sam
开发step functions
学习内容:
- 生成
sam
的step functions
实例程序 - 什么是
SAM amazon Serverless Application Model
SAM
程序结构SAM
执行程序
1. 生成sam
的step functions
实例程序
- 参照文档
这里参照AWS
的官方文档SAM amazon Serverless Application Model
- 什么是
SAM amazon Serverless Application Model
- 整体架构
SAM
就是一个基于Cloudformation
的应用程序框架,主要目的正如名字(Serverless Application Model
),方便进行Serverless Application
的开发。
开发的一般步骤如下:- 开发
lambda
等serverless application
。 - 利用
step functions
等serverless application
。当然,其中可以调用lambda
。 - 之后利用上面的
serverless application
,进行Cloudformation
的template
定义。 - 最后经过
sam build
和sam deploy
部署到AWS
的环境中。
- 开发
- 整体架构
3. SAM
程序结构
- 开始使用
SAM
- 这里使用
SAM
提供的实例程序进行练习HourlyTradingSchedule
是一个AWS EventBridge
的规则,这里定义了股票投资程序的调用周期。类似于linux
的cron job
。StockTradingStateMachine
就是股票交易的StateMachine
。- 股票交易的
StateMachine
里面包括三个lambda
StockCheckerFunction
这里随机产生股票的价格(进行简单的股票市场的模拟)- 中间其实有一个
choice state
,进行判断。这里没有画出来 - 之后根据判断,如果股票高过某个固定价格,那么进行
StockBuyerFunction
的调用 - 如果股票高过某个固定价格,那么进行
StockSellerFunction
的调用 - 最后,不管买还是卖的操作,都进行
TransactionTable
的写入(使用DynamoDB
记录交易)
- 进行实际代码的实验
- 实验环境
这里还是使用非常给力的工具CloudShell
。
- 构建代码
- 创建代码的父路径
mkdir demo-sam cd demo-sam
- 使用
sam
生成股票实例代码(这个代码是sam
自带的)
之后进行一些runtime
的相关设定。
到这里,代码就会被生成出来,而且cloudformation
的template
文件都是yaml
格式的。
- 创建代码的父路径
- 实验环境
- 将
cloudshell
环境中的代码通过S3
取到本地- 创建传输文件的
S3 bucket
因为cloudshell
不是很容易和本地传输文件,所以使用S3 bucket
。
- 将
SAM
代码打包,copy
到S3 bucket
tar zcvf demo-sam.tar.gz demo-sam/ aws s3 cp demo-sam.tar.gz s3://finlay-cloudshell/
- 将
SAM init
生成的实例程序代码,下载到本地
本地文件夹如下所示。
- 将
SAM init
生成的实例程序代码使用vscode
打开(这里单纯的可以更加容易编辑代码)template
文件AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: | demo-sam Sample SAM Template for demo-sam Resources: StockTradingStateMachine: Type: AWS::Serverless::StateMachine # More info about State Machine Resource: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-statemachine.html Properties: DefinitionSubstitutions: StockCheckerFunctionArn: !GetAtt StockCheckerFunction.Arn StockSellerFunctionArn: !GetAtt StockSellerFunction.Arn StockBuyerFunctionArn: !GetAtt StockBuyerFunction.Arn DDBPutItem: !Sub arn:${ AWS::Partition}:states:::dynamodb:putItem DDBTable: !Ref TransactionTable Events: HourlyTradingSchedule: Type: Schedule # More info about Schedule Event Source: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-statemachine-schedule.html Properties: Description: Schedule to run the stock trading state machine every hour Enabled: false # This schedule is disabled by default to avoid incurring charges. Schedule: rate(1 hour) Policies: # Find
- 创建传输文件的
- 这里使用