【问题标题】:Structure of a serverless application无服务器应用程序的结构
【发布时间】:2017-11-30 04:37:56
【问题描述】:

我是无服务器应用程序的新手。我按照 aws 教程使用 codestar 和 lambda 构建了一个简单的 nodejs 无服务器应用程序。

但是,想象一下这个节点应用程序做了很多事情。因此,它在 index.js 中有多个函数,一个用于功能 A,一个用于功能 B,等等(例如)。

我是否必须将多个 lambda 表达式(每个功能一个)附加到这个 codestar 项目?

【问题讨论】:

    标签: node.js aws-lambda serverless-architecture aws-codestar


    【解决方案1】:

    问题:我是否必须将多个 lambda 表达式(每个功能一个)附加到这个 codestar 项目? 答:是的

    AWS CodeStar 项目详情:

    AWS Code star 项目包含以下文件结构(reference link):

    README.md - this file
    buildspec.yml - this file is used by AWS CodeBuild to package your service for deployment to AWS Lambda
    app.js - this file contains the sample Node.js code for the web service
    index.js - this file contains the AWS Lambda handler code
    template.yml - this file contains the Serverless Application Model (SAM) used by AWS Cloudformation to deploy your service to AWS Lambda and Amazon API Gateway.
    

    假设你有如下的 template.yml 文件:

    AWSTemplateFormatVersion: 2010-09-09
    Transform:
    - AWS::Serverless-2016-10-31
    - AWS::CodeStar
    Resources:
      HelloWorld:
        Type: AWS::Serverless::Function
        Properties:
          Handler: index.first_handler
          Runtime: nodejs4.3
          Role:
            Fn::ImportValue:
              !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']]
          Events:
            GetEvent:
              Type: Api
              Properties:
                Path: /first
                Method: get
      HelloWorld2:
        Type: AWS::Serverless::Function
        Properties:
          Handler: index.second_handler
          Runtime: nodejs4.3
          Role:
            Fn::ImportValue:
              !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']]
          Events:
            GetEvent:
              Type: Api
              Properties:
                Path: /second
                Method: get
    

    请注意,在上面的 tamplate.yml 文件中指定了“HelloWorld”和“HelloWorld2”配置。

    • HelloWorld 配置包含“Handler”值为“index.first_handler”,这意味着“index”是 index.js 的文件名,first_handler 是 index.js 文件中的方法。
    • 同样,HelloWorld2 配置包含“Handler”值为“index.second_handler”,这意味着“index”是 index.js 的文件名,second_handler 是 index.js 文件中的方法。

    结论:

    您可以在 index.js (whatever.js) 文件中指定任意数量的 lambda 函数。只需指定适当的 Handler 来识别您的 lambda 函数的应用程序。

    希望这是您问题的答案。如有疑问,请随时提出疑问!

    【讨论】:

    • 下面的回复说你不能这样做。你试过了吗?
    【解决方案2】:

    您不需要多个处理函数 (index.js),也不能拥有多个处理函数。如果不同的功能正在执行逻辑分离的工作,那么您可以添加多个 JS 文件并在那里编写函数,但您应该将其引用到您的处理程序函数 (index.js)。或者,您可以在 index.js 本身中编写功能,但更好的想法和干净的代码是将逻辑上不同的功能分离到另一个文件并引用它

    【讨论】:

      猜你喜欢
      • 2017-04-08
      • 1970-01-01
      • 2021-09-23
      • 2018-03-08
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      相关资源
      最近更新 更多