当前位置: 首页 > 软件库 > 云计算 > Serverless 系统 >

lambda-refarch-webapp

授权协议 Apache-2.0 License
开发语言 JavaScript
所属分类 云计算、 Serverless 系统
软件类型 开源软件
地区 不详
投 递 者 祁辰阳
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Serverless Reference Architecture: Web Application

README Languages:PT

Introduction

The Web Application reference architecture is a general-purpose, event-driven, web application back-end that uses AWS Lambda, Amazon API Gateway for its business logic. It also uses Amazon DynamoDB as its database and Amazon Cognito for user management. All static content is hosted using AWS Amplify Console.

This application implements a simple To Do app, in which a registered user can create, update, view the existing items, and eventually, delete them.

Architectural Diagram

Application Components

The Web Application is built from 3 different components.

Front End Application

The front-end application is all the static content (HTML files, CSS files, JavaScript files and images) that are generated by create-react-app. All these objects are hosted on AWS Amplify Console.

When a user connects to the web site, the needed resources are downloaded to their browser and start to run there. When the application needs to communicate with the backend it does so by issuing REST API calls to the backend.

Back End Application (Business Logic)

The backend application is where the actual business logic is implemented. The code is implemented using Lambda functions fronted by an API Gateway REST API. In our case, we have different Lambda functions, each handling a different aspect of the application: list the to-do items, get details about a specific item, update an item, create a new item, mark an item as complete and delete an existing item. The application saves all items in a DynamoDB table.

User Registration and Authentication

As the ToDo application contains personal information (the user's ToDo items), access is restricted only to registered and authenticated users. Each user can access only their own items.

To accomplish this, we are using Cognito User Pools, which allows users to register to the application, authenticate and so on. Only after a user is authenticated, the client will receive a JWT token which it should then use when making the REST API calls.

Running the Example

Fork this repository to your own GitHub account, as you will need to create a Personal Access Token in Github for the Amplify console, as well as provide your GitHub repository URL in the deployment.

You can use the provided AWS SAM template to launch a stack that shown here on this Serverless reference architecture. Details about the resources created by this template are provided in the SAM Template Resources section of this document.

Generating your Github Access Token

In order for use the Amplify Console, you need to generate a personal access token.Once created, an access token should be stored in a safe place, as it may not be available to be seen the next time and may need to regenerate a new one again.In order to setup your access token, go to New personal access page in GitHub.

Note that you might need to enter your password in order to proceed.

Using SAM and the Amplify Console to Build and Deploy the Full Stack Application

You can deploy the full stack application using the deployment script:

export AWS_DEFAULT_REGION=<your preferred region, i.e. us-east-1>
export STACK_NAME=<a unique name for your CloudFormation stack>
./deploy.sh

The script will use the SAM CLI to build your backend functions, and then the guided deployment feature of the SAM CLI for the initial backend deployment. You will be prompted for a set of parameters, and can accept the defaults for all parameters with the exception of the GitHub Repository URL and the GitHub OAuth token.

Building the Application Step by Step

Alternatively, you could run the build steps yourself in the CLI:

Build the backend functions

The AWS SAM CLI comes with abstractions for a number of Lambda runtimes to build your dependencies, and copies the source code into staging folders so that everything is ready to be packaged and deployed. The sam build command builds any dependencies that your application has, and copies your application source code to folders under aws-sam/build to be zipped and uploaded to Lambda.

sam build --use-container

Package the backend

Next, run sam package. This command takes your Lambda handler source code and any third-party dependencies, zips everything, and uploads the zip file to your Amazon S3 bucket. That bucket and file location are then noted in the packaged.yaml file. You use the generated packaged.yaml file to deploy the application in the next step.

sam package \
    --output-template-file packaged.yml \
    --s3-bucket $DEPLOYMENT_BUCKET

Deploy the backend

This command deploys your application to the AWS Cloud. It's important that this command explicitly includes both of the following:

  • The AWS Region to deploy to. This Region must match the Region of the Amazon S3 source bucket.

  • The CAPABILITY_IAM parameter, because creating new Lambda functions involves creating new IAM roles.

sam deploy \
    --template-file packaged.yml \
    --stack-name $STACK_NAME \
    --capabilities CAPABILITY_IAM

Testing locally (Optional)

To run lambda function , API Gateway and dynamodb locally follow the steps

To run the dynamodb table locally

docker run -p 8000:8000 amazon/dynamodb-local

Create a table in local Dynamodb environment

aws dynamodb create-table --table-name TodoTable --attribute-definitions AttributeName=id,AttributeType=S --key-schema AttributeName=id,KeyType=HASH --billing-mode PAY_PER_REQUEST --endpoint-url http://127.0.0.1:8000

Run the sam local module to test the application locally

sam local start-api --env-vars todo-src/test/environment/mac.json

Sample file of mac os is todo-src/test/environment/mac.json

Updating the Front-End Application

Once you deploy the infrastructure using SAM you will need to create a configuration file for your front-end web application. You can view the necessary values by describing your deployed stack:

aws cloudformation describe-stacks --stack-name $STACK_NAME --query "Stacks[0].Outputs[]"

Copy the default config file and update the values from the output above:

cp www/src/config.default.js www/src/config.js

You can run the front end locally for testing by setting the redirect_url value to https://localhost:8080 and running:

cd www/src
npm start

You can run the front end locally for testing and use the local api by setting the api_base_url value to http://127.0.0.1:8080

Deploy the frontend

Deploy your application by checking in your update to the config.js file and pushing that commit to your repo. Amplify Console will automatically deploy the update from there.

git add www/src/config.js
git commit -m 'Update frontend config'
git push

You can view the deployment process in the Amplify Console web console.

Cleaning Up the Example Resources

Delete the CloudFormation Stack

aws cloudformation delete-stack \
--stack-name $STACK_NAME

Delete the CloudWatch Log Groups

for log_group in $(aws logs describe-log-groups --log-group-name-prefix '/aws/lambda/'$STACK_NAME --query "logGroups[*].logGroupName" --output text); do
  echo "Removing log group ${log_group}..."
  aws logs delete-log-group --log-group-name ${log_group}
  echo
done

SAM Template Resources

Resources

The provided templatecreates the following resources:

  • TodoUserPool - A Cognito UserPool that holds all the application users

  • TodoUserPoolTokenClient - A Cognito UserPool Client used by the web application

  • TodoDomain - The Cognito UserPool domain name

  • TodoTable - The DynamoDB table used to hold all the ToDo items for all users

  • TodoApi - The REST API that is used to expose the ToDo application functionality

  • GetTodoFunction - The Lambda function used to retrieve a single ToDo item

  • GetAllTodoFunction - The Lambda function used to retrieve all the ToDo items

  • CompleteTodoFunction - The Lambda function used to set the state of an item to complete

  • AddTodoFunction - The Lambda function used to create a new ToDo item

  • UpdateTodoFunction - The Lambda function used to update the content of a ToDo item

  • DeleteTodoFunction - The Lambda function used to delete a ToDo item

  • ApiGatewayPushToCloudWatchRole - An IAM role that allows API Gateway to send log events to CloudWatch Logs

  • ApiAccessLogGroup - The CloudWatch Logs Log Group used by API Gateway for its log messages

  • AmplifyApp - Amplify Console application that will manage deployment of frontend updates based on pushes to GitHub

  • AmplifyBranch - Connecting a GitHub branch to the Amplify Console application

  • AmplifyRole - An IAM role that allows the Amplify Console to perform build and deployment actions

Notes

By default, the default Node.js HTTP/HTTPS agent creates a new TCP connection for every new request. To avoid the cost of establishing a new connection, you can reuse an existing connection.

For short-lived operations, such as DynamoDB queries, the latency overhead of setting up a TCP connection might be greater than the operation itself. Additionally, since DynamoDB encryption at rest is integrated with AWS KMS, you may experience latencies from the database having to re-establish new AWS KMS cache entries for each operation.

The easiest way to configure SDK for JavaScript to reuse TCP connections is to set the AWS_NODEJS_CONNECTION_REUSE_ENABLED environment variable to 1. This feature was added in the 2.463.0 release.

Read more about this feature on our Developer Guide.

Well-Architected Review

We have conducted a Well-Architected review for this application using the Serverless Application Lens. The results of this review can be found here.

License

This reference architecture sample is licensed under Apache 2.0.

  • filter函数 filter(self, /, *args, **kwargs)-----过滤 filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。 该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。 例如:实例 def is_odd(n): r

  • 一.简介 Java 8引入了一些新的语言功能,旨在更快,更清晰地编码。它具有最重要的功能,即所谓的“ Lambda表达式”,为函数式编程打开了大门。Lambda表达式允许以直接方式实现和传递函数,而无需声明其他(匿名)类。 注意: Flink支持对Java API的所有运算符使用lambda表达式,但是,每当lambda表达式使用Java泛型时,都需要显式声明类型信息。 二.范例与限制 下面的示例

  • 1.配合mybatis-plus使用   1.1 数据的操作 lambdaQuery.select(UserCarBinding::getRegistrationId) //select值 .eq(UserCarBinding::getRegistrationId, userId) .eq(UserCarBinding::getDe

  • public class WordCountA { public static void main(String[] args) throws Exception { ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); String path = "xxx/hello.txt"; DataSet in

  • InputStream inputStream = Version.class.getClassLoader().getResourceAsStream("/META-INF/MANIFEST.MF"); String version = DEFAULT_VERSION; Manifest manifest = new Manifest(inputStream); Attribut

  • 就目前而言,Lambda的向后兼容性和稳定性都是不可预测和无法保障的,因此并不建议在企业项目中使用 引入 为了支持函数式编程,Java 8引入了Lambda表达式,Android N已经开始支持Java 8 了。使用Lambda可以大大减少代码的编写,只关注最重要的部分(形参和函数体),虽然使代码的可读性变差,但用习惯了就会喜欢上Lambda表达式,它使代码变得干净整洁了不是一点半点。 Lambd

  • Map: 对于简单的map(i -> i * i) flink 可以猜测其 类型。复杂的则需要指定return type,或者构造一个MapFunction,或者extends 自 Tuple2<Integer, Integer>。 flatMap:对于flatMap 的支持是无法猜测出来 类型的,必须通过returns(Types.STRING) 指定具体的返回值类型。 package myfl

  • lambda - foreach lambda 语法格式: (parameters) -> expression (parameters) -> {statements;} /** * Map<String,Integer></> */ public static void testMap() { Map<String, Integer> map

 相关资料
  • ECS Reference Architecture: Continuous Deployment The ECS Continuous Deployment reference architecture demonstrates how to achievecontinuous deployment of an application to AmazonElastic Container Ser

  • 问题内容: 我正在尝试执行新的JDK 8函数式编程领域中似乎是相对基本的事情,但是我无法使其工作。我有这个工作代码: 它接受一个数字列表,并产生可以打印出来的功能列表。但是,显式强制转换为Callable似乎是多余的。在我和IntelliJ中看来。我们都同意这也应该起作用: 但是我得到一个错误: 问题答案: 您遇到了Java 8目标类型的限制,该限制适用于方法调用的 接收者 。尽管目标类型在大多数

  • 我正试图做一件在新JDK似乎是相对基本的事情 它获取一个数字列表并生成一个可以将它们打印出来的函数列表。然而,Callable的显式强制执行似乎是多余的。对我和IntelliJ来说似乎是这样。我们都同意这也应该有效: 但是,我收到一个错误:

  • 有时您可能只需要在程序中的一个位置使用一个函数,并且该函数非常简单,您可能不会给它命名,或者可能不想将它存储在符号表中,而宁愿编写一个未命名或匿名的函数。 LISP允许您编写仅在程序中遇到它们时才计算的匿名函数。 这些函数称为Lambda functions. 您可以使用lambda表达式创建此类函数。 lambda表达式的语法如下 - (lambda (parameters) body) 无法

  • 头文件: "boost/lambda/lambda.hpp" 它包括了本库的核心部分。 "boost/lambda/bind.hpp" 它定义了 bind 函数。 "boost/lambda/if.hpp" 它定义了相当于 if 的 lambda ,以及条件操作符。 "boost/lambda/loops.hpp" 它定义了循环结构(例如,while_loop 和 for_loop)。 "b

  • AWS Lambda是一种响应式云服务,可检查应用程序中的操作,并通过部署用户定义的代码(称为functions响应。 它可以自动管理多个可用区域中的计算资源,并在触发新操作时对其进行扩展。 AWS Lambda支持使用Java,Python和Node.js编写的代码,该服务可以使用Amazon Linux支持的语言(包括Bash,Go和Ruby)启动流程。 以下是使用AWS Lambda时的一些