Lambda + DynamoDB + API Gateway + Serverless Framework
之前的例子中,通过Sls简单生成了 Lambda 函数,
接下来,实例学习 DynamoDB 和 API Gateway 的联动。
应用示意图
客户端通过http访问 aws api 网关;
网关触发 lambda 函数;
函数将一些内容写入 dynamoDB;
serverless实现客户端的 deploy
SLS的结构生成
参照之前的例子生成 SLS 应用的结构: 使用Serverless构建无服务器应用.
DynamoDB生成
在 serverless.yml 内
添加 resources 部分,生成 sls-user 表,主key是 id
[vagrant@localhost sampleSls]$ cat serverless.yml
service: sampleSls
provider:
name: aws
runtime: nodejs8.10
stage: dev
region: ap-northeast-1
functions:
hello:
handler: handler.hello
resources:
Resources:
DemoDynamoDbTable:
Type: 'AWS::DynamoDB::Table'
Properties:
AttributeDefinitions:
-
AttributeName: id
AttributeType: S
KeySchema:
-
AttributeName: id
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
TableName: sls-user
DynamoDB生成确认
[vagrant@localhost sampleSls]$ sls deploy -v
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service .zip file to S3 (387 B)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
......
可以通过console确认 DynamoDB 已经被生成
DynamoDB的表里添加数据
$ aws dynamodb put-item --table-name sls-user --item '{"id": {"S": "001"}, "name": {"S": "test01"}}' --region ap-northeast-1
$ aws dynamodb put