使用 Node.js 快速开启 ServerLess Functions:入门实践指南

    Serverless 意为 “无服务器架构”,但是这并不意味着真的就无需服务器了,这些服务器的管理由云计算平台提供,对于用户侧无须关注服务器配置、监控、资源状态等,可以将重点放在业务逻辑上。

    下图,将 Microservices 进一步细分为 Function as a Service(FaaS)函数即服务,相比微服务颗粒度更小。

    图片来源:

    ServeLess 进一步了解

    ServerLess 是什么?网上有很多关于这些的介绍,也许你可以参考,下面列举一些之前的分享:

    云厂商的支持

    截止目前已有很多云厂商支持 ServerLess:

    在本节示例中将使用 Aws Lambda,你可以选择上面列举的其它的服务商都是可以的,AWS 提供一年的免费试用,但是在使用 AWS 服务之前你需要先拥有一张有效的信用卡进行绑定,第一次 AWS 会扣除 1 美元的金额进行验证。

    以下几步需要你先完成:

    ServerLess 框架安装和配置

    安装 serveless 框架

    检查 serverless 是否安装成功

    1. Framework Core: 1.60.0
    2. Plugin: 3.2.6
    3. SDK: 2.2.1
    4. Components Core: 1.1.2
    5. Components CLI: 1.4.0

    设置 AWS Credentials

    如果已经设置了,可能会失败,在 serverless config credentials 后面加上 -o 即可。

    1. $ serverless config credentials --provider aws --key <your_access_key_id> --secret <your_access_key_secret>
    2. Serverless: Setting up AWS...

    通过 serverless CLI 工具可以快速创建一个项目,—template 是该脚手架所支持的模板,更多模版可参考

    1. $ serverless create --template hello-world --path aws-hello-nodejs-function
    2. Serverless: Generating boilerplate...
    3. Serverless: Generating boilerplate in "/Users/test/aws-hello-nodejs-function"
    4. _______ __
    5. | _ .-----.----.--.--.-----.----| .-----.-----.-----.
    6. | |___| -__| _| | | -__| _| | -__|__ --|__ --|
    7. |____ |_____|__| \___/|_____|__| |__|_____|_____|_____|
    8. | | | The Serverless Application Framework
    9. | | serverless.com, v1.60.0
    10. Serverless: Successfully generated boilerplate for template: "hello-world"

    创建成功后可以看到如下项目结构

    handler.js 是逻辑处理的地方,当然你也可以自定义其它的文件,一旦自定义文件之后需要在 serverless.yml 文件里也进行响应更改,本节只是入门所以不会太复杂,后续会出一个使用 ServerLess 实现的 RESTFULL API 实践,可以关注公众号 “Nodejs技术栈” 获取最新消息。

    以下有三个参数是你需要了解的:

    • event:用来解析请求的数据
    • context:使用 context 将运行时参数传递给 Lambda 函数
    • callback 返回响应数据
    1. 'use strict';
    2. module.exports.helloWorld = (event, context, callback) => {
    3. const response = {
    4. statusCode: 200,
    5. headers: {
    6. 'Access-Control-Allow-Origin': '*', // Required for CORS support to work
    7. },
    8. body: JSON.stringify({
    9. message: 'Go Serverless v1.0! Your function executed successfully!',
    10. input: event,
    11. };
    12. callback(null, response);
    13. };
    • service:服务名称
    • provider:定义你的服务需要部署的位置
    • functions:定义要部署的代码
    • functions.helloWorld:函数
    • functions.helloWorld.handler:value 中的 “handle.helloWorld” 定义了函数文件的路径,handle 文件下的 helloWorld 函数
    • functions.helloWorld.events:events 定义了如何触发 “handler.helloWorld” 程序
    1. service: aws-hello-nodejs-function
    2. provider:
    3. name: aws
    4. runtime: nodejs12.x
    5. functions:
    6. helloWorld:
    7. handler: handler.helloWorld
    8. events:
    9. - http:
    10. path: hello-world # 定义请求路径
    11. method: get # 定义接口请求方式
    12. cors: true # 开启跨域

    部署

    列举一些 ServerLess 部署相关的命令:

    • 部署全部$ serverless deploy
    • 单个部署$ serverless deploy function -f helloWorld
    • 本地触发一个函数测试$ serverless invoke local -f helloWorld
    1. $ serverless deploy
    2. Serverless: Packaging service...
    3. Serverless: Excluding development dependencies...
    4. Serverless: Creating Stack...
    5. Serverless: Checking Stack create progress...
    6. ........
    7. Serverless: Stack create finished...
    8. Serverless: Uploading CloudFormation file to S3...
    9. Serverless: Uploading artifacts...
    10. Serverless: Validating template...
    11. Serverless: Updating Stack...
    12. Serverless: Checking Stack update progress...
    13. .................................
    14. Serverless: Stack update finished...
    15. Service Information
    16. service: aws-hello-nodejs-function
    17. stage: dev
    18. region: us-east-1
    19. stack: aws-hello-nodejs-function-dev
    20. resources: 12
    21. api keys:
    22. None
    23. endpoints:
    24. GET - https://******.execute-api.us-east-1.amazonaws.com/dev/hello-world
    25. functions:
    26. helloWorld: aws-hello-nodejs-function-dev-helloWorld
    27. layers:
    28. None
    29. Serverless: Run the "serverless" command to setup monitoring, troubleshooting and testing.

    以上日志中的 endpoints 展示了访问的接口地址,现在你可以通过接口来调用,或者 postman、curl 访问。

    本地测试 ServerLess-Offline

    使用这个 serverless-offline 插件可以在本地启动一个 HTTP 服务器模拟 AWS λ 和 API Gateway。

    安装插件,如果本地没有 package.json 文件,可以 npm init 生成一个 package.json 文件

    1. $ npm install serverless-offline --save-dev

    修改 serverless.yml

    在项目的 serverless.yml 里添加插件 serverless-offline,如下所示:

    1. plugins:
    2. - serverless-offline

    本地启动

    项目根目录执行 serverless offline 命令,就可成功的在本地开启测试

    1. $ serverless offline
    2. Serverless: Starting Offline: dev/us-east-1.
    3. Serverless: Routes for helloWorld:
    4. Serverless: GET /hello-world
    5. Serverless: POST /{apiVersion}/functions/aws-hello-nodejs-function-dev-helloWorld/invocations
    6. Serverless: Offline [HTTP] listening on http://localhost:3000

    默认地址为 http://localhost:3000 如下所示就可轻松的访问我们上面的例子

    serverless-offline 提供了很多选项是可以让你自定义的,例如修改启动项目监听的端口,可以参考

    本节 Github 源码地址如下:

    通过本节入门指南,希望你能掌握如何去开启一个 ServerLess 应用程序以及如何部署、在本地进行开发调试,这只是一个开始,下一节我将在这个基础之上使用 ServerLess、Node.js 和 MongoDB Atlas cloud 构建一个 REST API,敬请关注公众号 “Nodejs技术栈” 获取最新信息。

    Reference