什么是 Serverless?
Serverless 架构指的是一种无需关心服务器运维的应用架构。在传统的应用架构中,我们需要自己租用服务器、安装配置操作系统、运维各类服务(如 Web 服务器、数据库等),才能部署和运行应用。而 Serverless 架构则是将这些运维工作交给云服务商,让开发者能够专注于业务逻辑的实现,大大降低了运维成本。
Serverless 常用的云服务商
当前比较主流的 Serverless 云服务商有 AWS Lambda、Google Cloud Functions、Microsoft Azure Functions 等。本文以 AWS Lambda 为例进行介绍。
准备工作
在使用 AWS Lambda 开发 Serverless 应用之前,需要完成以下准备工作:
Lambda 的基本概念
在 AWS Lambda 中,每个应用都是由一个个函数组成的。Lambda 函数是一段 JavaScript 代码,当触发器(如 API Gateway、S3 等)将数据传递给该函数时,Lambda 会自动创建一个运行环境,并将数据传递给该函数。函数执行完毕后,将会自动回收运行环境。这种无需关心服务器运维的方式,使得 Serverless 应用越来越受到欢迎。
开始开发
第一步:创建 Lambda 函数
使用 AWS CLI 创建 Lambda 函数的命令如下:
aws lambda create-function \ --function-name myFunction \ --runtime nodejs12.x \ --role myRole \ --handler index.handler \ --code S3Bucket=myBucket,S3Key=myKey
其中,myFunction 表示函数名称,nodejs12.x 表示使用 Node.js 12.x 运行环境,myRole 表示执行该函数的角色,index.handler 表示函数代码入口文件和函数名(入口文件为 index.js,函数名为 handler),myBucket 和 myKey 表示存储函数代码的 S3 存储桶和文件名。
第二步:编写 Lambda 函数代码
假设我们需要将 API Gateway 的请求参数通过 Lambda 函数传递给 Amazon S3,代码如下:
// www.javascriptcn.com code example
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
exports.handler = async (event) => {
const params = {
Bucket: 'myBucket',
Key: 'myKey',
Body: JSON.stringify(event),
};
await s3.putObject(params).promise();
return {
statusCode: 200,
body: 'OK',
}
};该 Lambda 函数将 API Gateway 的请求参数转为 JSON 格式,并将其保存到指定的 S3 存储桶中。
第三步:创建 API Gateway 触发器
使用 AWS CLI 创建 API Gateway 触发器的命令如下:
// www.javascriptcn.com code example
aws apigateway create-rest-api --name myAPI
aws apigateway get-resources --rest-api-id myAPI
aws apigateway create-resource --rest-api-id myAPI --parent-id xxx --path-part myPath
aws apigateway put-method \
--rest-api-id myAPI \
--resource-id xxx \
--http-method POST \
--authorization-type NONE \
--no-api-key-required
aws apigateway put-integration \
--rest-api-id myAPI \
--resource-id xxx \
--http-method POST \
--type AWS \
--integration-http-method POST \
--uri arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:111111111111:function:myFunction/invocations \
--passthrough-behavior WHEN_NO_TEMPLATES \
--no-content-handling
aws apigateway put-method-response \
--rest-api-id myAPI \
--resource-id xxx \
--http-method POST \
--status-code 200 \
--response-models '{"application/json": "Empty"}'
aws apigateway put-integration-response \
--rest-api-id myAPI \
--resource-id xxx \
--http-method POST \
--status-code 200 \
--selection-pattern ""
aws apigateway create-deployment \
--rest-api-id myAPI \
--stage-name prod第四步:测试应用
执行以下命令,请求 API Gateway:
curl -X POST "https://xxxxxx.execute-api.us-east-1.amazonaws.com/prod/myPath" -H "Content-Type: application/json" -d '{ "name": "Bob", "age": 18 }'根据观察请求后,我们可以看到请求成功发送到了 Lambda 函数中,并将请求参数转为 JSON 格式后存储到了指定的 S3 存储桶中。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67cfae78e46428fe9eb7e1a7