AWS亚马逊云计算技术Serverless

Serverless 入门(三)- 初始项目解读

2019-03-09  本文已影响1人  Kenny锅

执行 serverless create --template aws-nodejs --path hello-world 后,就会在当前目录生成一个名为 hello-world

代码目录结构如下:

├── .gitignore
├── handler.js
└── serverless.yml

1. .gitignore

.gitignore 里有3个忽略项,分别如下:

2. handler.js

module.exports.hello = async (event, context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Go Serverless v1.0! Your function executed successfully!',
      input: event,
    }),
  };
};

handler.js 是用 --template aws-nodejs 参数生成出来的 js 文件, 代码就是输出一个 JSON。
注:如果我们选用 aws-nodejs-typescript 模块,就会生成 handler.ts 文件。如果你用 Microsoft Azure 服务,也可以选用 azure-nodejs 模板。关于更多项目模板,我后面章节会细讲,请关注哦!

3. serverless.yml

这是 yml 文件里除注释外的代码

service: hello-world
provider:
  name: aws
  runtime: nodejs8.10
functions:
  hello:
    handler: handler.hello

这相当于 serverless 的描述文件,介绍了服务名为hello-world,服务提供商是 aws,运行环境是nodejs 8.10 版

你可能要问,一定要是 nodejs8.10 吗?我要用 Node 10 行不行? 答案是:不行!!!

runtime 目前只支持:java8, nodejs6.10, nodejs8.10, python2.7, python3.6, dotnetcore1.0, dotnetcore2.0, dotnetcore2.1, go1.x (截止2019-3-9)

第 6 行的 hello: 是调用时的名称,如果改成 hellokenny:,调用时就要用 serverless invoke -f hellokenny

第 7 行的 handler: 是不能乱改的, 如果你以后发现 Missing "handler" property in function "hello",首先就应该检查一下,是不是把 handler: 改错了。
第 7 行的 handler.hello 我们分两部分来讲,点号(.)前面的 handler 是文件名,后面的 hello 是默认函数名。

我们如果把项目根目录的 handler.js 改为 index.js,那就要把 serverless.yml 里的内容改为 handler: index.hello

4. 最后

当我们执行过 serverless deploy 之后就会变成如下目录结构:

├── .gitignore
├── .serverless
│   ├── cloudformation-template-create-stack.json
│   ├── cloudformation-template-update-stack.json
│   ├── hello-world.zip
│   └── serverless-state.json
├── handler.js
└── serverless.yml
  "service": {
    "service": "hello-world",
    "serviceObject": {
      "name": "hello-world"
    },
    "provider": {
      "stage": "dev",
      "region": "us-east-1",
      "variableSyntax": "\\${([ ~:a-zA-Z0-9._@'\",\\-\\/\\(\\)]+?)}",
      "name": "aws",
      "runtime": "nodejs8.10",
      "versionFunctions": true,

关于更多serverless.yml,后面相关章节会再讲。

相关文章

上一篇 下一篇

猜你喜欢

热点阅读