无服务器应用程序的结构

时间:2017-11-30 04:37:56

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

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

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

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

2 个答案:

答案 0 :(得分:2)

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

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"和#34; HelloWorld2"配置。

  • HelloWorld配置包含" Handler"值为" index.first_handler"意思是"索引"是index.js的文件名,first_handler是index.js文件中的方法。
  • 同样,HelloWorld2配置包含" Handler"值为" index.second_handler"意思是"索引"是index.js的文件名,second_handler是index.js文件中的方法。

<强>结论:

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

希望这是你问题的答案。如果有的话,请随意提出疑问!

答案 1 :(得分:0)

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

相关问题