什么是 Serverless?
Serverless 是一种全新的构建应用程序的方式,其最大的特点是无需关注服务器,让开发者可以专注于业务逻辑,不必再担心部署、扩展与维护等问题。相比于传统的基础架构,Serverless 更加灵活、便捷,还能够帮助我们降低开发成本。
Serverless Framework
Serverless Framework 是一个免费的、开源的、跨云平台的 Serverless 应用程序架构,它可以帮助开发者通过高层次的抽象,更轻松地构建、部署和操作 Serverless 应用程序。Serverless Framework 很适合构建后端应用、API 服务、处理事件等场景。
搭建 Serverless API Gateway
Step 1:安装 Serverless Framework
npm install -g serverless
Step 2:创建 Serverless 项目
serverless create --template aws-nodejs --path serverless-api-gateway cd serverless-api-gateway
在上面的命令中,我们创建了一个名为 serverless-api-gateway 的 Serverless 项目,并选择了 aws-nodejs 模板作为我们的应用程序的起点。
Step 3:配置 Serverless 项目
在项目的根目录下创建一个名为 serverless.yml 的文件,它是 Serverless 应用程序的核心配置文件:
// www.javascriptcn.com code example
service: serverless-api-gateway
provider:
name: aws
runtime: nodejs12.x
functions:
hello:
handler: handler.hello在上文中,我们使用了 AWS Lambda 作为我们的 Serverless provider,设置 name 为 aws,表示我们希望将应用程序部署到 AWS 平台上。runtime 为 nodejs12.x,表示我们将使用 Node.js 12.x 运行环境。functions 中定义了我们应用程序需要的各个函数,比如在这个例子里我们只有一个名为 hello 的函数。
Step 4:编写代码逻辑
在 handler.js 中编写实际的处理逻辑:
module.exports.hello = async (event, context) => {
return {
statusCode: 200,
body: JSON.stringify({
message: 'Hello World!',
}),
};
};以上代码定义了一个名为 hello 的函数,它会返回一个包含 'Hello World!' 文字的 JSON 数据。
Step 5:部署 Serverless 应用程序
执行如下命令部署 Serverless 应用程序:
serverless deploy
部署完成之后,输出类似如下的提示信息:
// www.javascriptcn.com code example Service Information service: serverless-api-gateway stage: dev region: us-east-1 stack: serverless-api-gateway-dev resources: 8 api keys: None endpoints: GET - https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/hello functions: hello: serverless-api-gateway-dev-hello layers: None
其中,endpoints 表示我们构建的 Serverless API Gateway 的访问地址。这里,它为 https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/hello。
Step 6:验证 Serverless API Gateway
访问 https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/hello,即可看到如下结果:
{
"message": "Hello World!"
}到此为止,我们使用 Serverless Framework 搭建了一个 Serverless API Gateway,非常简单又高效。结合云厂商的 Serverless 服务,可以让开发者更加专注于业务逻辑的处理,从而提高开发效率。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67cfae75e46428fe9eb7e175