当前位置: 首页 > 编程日记 > 正文

node aws 内存溢出_如何使用Node.js和AWS快速创建无服务器RESTful API

node aws 内存溢出

by Mark Hopson

马克·霍普森(Mark Hopson)

如何使用Node.js和AWS快速创建无服务器RESTful API (How to quickly create a serverless RESTful API with Node.js and AWS)

In this beginner’s guide, we’ll briefly describe the “Serverless” software architecture, and then create a RESTful API using AWS, Node.js, and Swagger in a few short minutes.

在本初学者指南中,我们将简要描述“无服务器”软件架构,然后在短短几分钟内使用AWS,Node.js和Swagger创建RESTful API。

那么什么是无服务器的? (So what’s Serverless?)

The term Serverless (a.k.a. Functions-as-a-Service) describes a type of architecture that allows code to be deployed to, and run on, ephemeral and stateless containers from third-party vendors (like Azure or AWS).

无服务器(又称“功能即服务”)一词描述了一种体系结构,该体系结构允许将代码部署到第三方供应商(例如Azure或AWS)的临时和无状态容器中并在其上运行。

无服务器的好处 (Serverless Benefits)

  • Reduced operational management. Serverless architectures allows developers to focus on writing code, and not worry about configuring and managing the infrastructure that their code runs on.

    减少运营管理。 无服务器架构允许开发人员专注于编写代码,而不必担心配置和管理其代码所基于的基础架构。

  • Easy, flexible scaling. Since Serverless “functions” (your Serverless applications) are stateless and always invoked by an event (like an HTTP request), you can run as many, or as few, functions as you need. More invocations mean more containers. Depending on the scale and shape of your traffic, this can be very cost efficient, since Serverless functions are typically billed per invocation.

    轻松灵活的缩放比例。 由于无服务器“功能”(您的无服务器应用程序)是无状态的,并且总是由事件(例如HTTP请求)调用,因此您可以根据需要运行任意数量的功能。 更多的调用意味着更多的容器。 取决于流量的规模和形状,这可能非常具有成本效益,因为无服务器功能通常按调用计费。

无服务器的缺点 (Serverless Drawbacks)

  • Latency for initial requests (known as “cold starts”). If the Serverless function is inactive (has not been run in a while), then handling the first invocation can require extra time to complete because the container will have to initialize (that is, allocate host, load code, and so on).

    初始请求的延迟(称为“冷启动”)。 如果无服务器功能处于非活动状态(已经一段时间未运行),则处理第一次调用可能需要额外的时间才能完成,因为容器将必须初始化(即分配主机,装入代码等)。

  • Lack of system control. Since your code is running in an environment managed by a vendor, you won’t be able to control system upgrades, or dependencies outside of your code base.

    缺乏系统控制 。 由于您的代码在供应商管理的环境中运行,因此您将无法控制系统升级或代码库之外的依赖项。

什么是CloudFormation? (And what’s CloudFormation?)

CloudFormation is a service from Amazon that allows you to build AWS resources using templates. A template is a configuration file (YML or JSON) for provisioning all your AWS resources such as EC2 instances, DynamoDB tables, IAM roles and permissions, or anything else.

CloudFormation是Amazon提供的一项服务,可让您使用模板构建AWS资源。 模板是一个配置文件(YML或JSON),用于供应您的所有AWS资源,例如EC2实例,DynamoDB表,IAM角色和权限或其他任何资源。

让我们开始编码! (Let’s Start Coding!)

In this tutorial, we are going to make a simple RESTful API with the following two endpoints:

在本教程中,我们将使用以下两个端点制作一个简单的RESTful API:

POST / users / $ {userId} / hello (POST /users/${userId}/hello)

The request body will be saved in a DynamoDB table. In this tutorial, the request body must have this structure: { "email": "any@email.com" }

请求正文将保存在DynamoDB表中。 在本教程中,请求正文必须具有以下结构: { "email": "any@email.com" }

GET / users / $ {userId} / hello (GET /users/${userId}/hello)

The response will contain the value for "email" set in the POST request.

响应将包含在POST请求中设置的"email"值。

第1步:克隆仓库 (Step 1: Clone the repo)

There are two files that you need for this tutorial: index.js (the NodeJS code for our Lambda function) and stack.yml (the CloudFormation stack template). To get these files, visit this Github link.

本教程需要两个文件: index.js (Lambda函数的stack.yml代码)和stack.yml ( stack.yml堆栈模板)。 要获取这些文件,请访问此 Github链接。

步骤2:检查stack.yml文件 (Step 2: Examine the stack.yml file)

Pay attention to the stack.yml in the repo, as it is the config file that will be used by CloudFormation to create everything our application will require.

请注意回购中的stack.yml ,因为stack.yml将使用该配置文件来创建应用程序所需的一切。

Below is a detailed diagram of all the AWS resources our stack.yml will need to create. The names that are used in the YML are in the red boxes.

以下是我们stack.yml需要创建的所有AWS资源的详细图表。 YML中使用的名称在红色框中。

步骤3:上传您的CloudFormation模板 (Step 3: Upload your CloudFormation Template)

After you check out the YML, head over to this link and click the Create Stack button. Choose Upload a template to Amazon S3 and upload the stack.yml file.

签出YML后,转到此链接 ,然后单击“ 创建堆栈”按钮。 选择上载模板到Amazon S3并上载stack.yml文件。

On the next screen, you will be ask to pick a Stack name (can be anything). After this, click Next and select I acknowledge that AWS CloudFormation might create IAM resources, and click Next again.

在下一个屏幕上,将要求您选择堆栈名称 (可以是任何名称 )。 之后,单击下一步,然后选择我确认AWS CloudFormation可能会创建IAM资源 ,然后再次单击下一步

At this point, your stack is being created. Wait a minute on the Stacks page until your stack’s status becomes CREATE_COMPLETE.

此时,正在创建您的堆栈。 在“堆栈”页面上等待一分钟,直到您的堆栈状态变为CREATE_COMPLETE为止

步骤4:查找由CloudFormation创建的Lambda (Step 4: Find your Lambda created by CloudFormation)

Once your stack is complete, go and find your stack’s new Lambda here. Your Lambda’s Function name should resemble ${StackName}-HelloLambda-XXXX.

堆栈完成后,请在此处找到堆栈的新Lambda。 您的Lambda的函数名称应类似于$ {StackName} -HelloLambda-XXXX

步骤5:将代码部署(复制并粘贴)到Lambda (Step 5: Deploy (copy and paste) your code to your Lambda)

Once you’ve found your Lambda, click on it for more details. Then scroll to the Function Code section, change the Code entry type to Edit code inline, then open and copy index.js (from the repo) into the code editor. Click Save.

找到Lambda后,请单击它以获取更多详细信息。 然后滚动到“ 功能代码”部分,将“ 代码”输入类型更改为 内联编辑代码” ,然后打开并将index.js (从仓库中)复制到代码编辑器中。 点击保存

At this point, your code has been “deployed” to the Lambda, and all that’s left is to deploy our API Gateway so we can send HTTP requests to it.

至此,您的代码已“部署”到Lambda,剩下的就是部署我们的API网关,以便我们可以向其发送HTTP请求。

步骤6:查找由CloudFormation创建的API网关 (Step 6: Find your API Gateway that was created by CloudFormation)

Find your API Gateway created by your CloudFormation template here. Your API Gateway’s name should resemble ${StackName}-MyApiGateway.

在此处找到由CloudFormation模板创建的API网关。 您的API网关的名称应类似于$ {StackName} -MyApiGateway

步骤7:测试您的API网关是否已连接到Lambda (Step 7: Test if your API Gateway is hooked up to Lambda)

After you found your API Gateway, we can test to see if everything is hooked up by selecting the POST option under /users and then clicking TEST .

找到您的API网关后,我们可以通过选择/ users下的POST选项,然后单击TEST测试是否已挂接所有内容

On the Test page, set userId to 123, and set the Request Body to the following and click Test. If everything worked, the Status should be 200 with no data.

在“测试”页面上,将userId设置为123,并将“ 请求 正文”设置为以下内容,然后单击“ 测试” 。 如果一切正常, 状态应为200 ,无数据。

After testing the POST endpoint, you can check to see if your data was saved by going to the /hello GET Test page and trying a request (remember to set userId to 123). The response body should contain the Request Body from the POST test (see above).

测试POST端点之后,可以转到/ hello GET Test页面并尝试请求(请记住将userId设置为123),以查看是否保存了数据。 响应主体应包含POST测试中的请求主体(请参见上文)。

Now that you’ve verified that your API Gateway, Lambda, and DynamoDB are hooked up, you can deploy your API Gateway so you can reach it from the internet.

既然您已经确认API网关,Lambda和DynamoDB已连接,则可以部署API网关,以便从Internet进行访问。

步骤8:部署您的API网关 (Step 8: Deploy your API Gateway)

To deploy your API, click the Actions menu and select Deploy API. Once the confirmation pop-up appears, set Deployment stage to prod and then click Deploy.

要部署您的API,请单击“操作”菜单,然后选择“部署API”。 出现确认弹出窗口后,将Deployment stage设置为prod ,然后单击Deploy

Once you’ve deployed your API, you will be forwarded to the Stages page for prod. Here you will find the domain for your API Gateway in the blue highlighted area beside Invoke URL.

部署API后,您将转到prod的“ 阶段”页面。 在此处,您可以在Invoke URL旁边的蓝色突出显示区域中找到API网关的域。

Using the URL from the screenshot above, I should be able to send a GET /users/123/hello request in my web browser like below.

使用上面的屏幕快照中的URL,我应该能够在Web浏览器中发送GET / users / 123 / hello请求,如下所示。

And that’s it! You now have a Serverless RESTful API that is scalable, reliable, doesn’t require patching or provisioning, and doesn’t cost money when idle. I hope you’ve enjoyed this tutorial, and if you have any feedback, please leave it in the comments below. Thanks!

就是这样! 现在,您有了一个无服务器RESTful API,该API具有可伸缩性,可靠性,不需要修补或置备,并且在空闲时也不需要花钱。 希望您喜欢本教程,如果有任何反馈,请留在下面的评论中。 谢谢!

其他说明和标注 (Other Notes and Callouts)

  • The route configuration for API Gateway is embedded inside the API Gateway (MyApiGateway) configuration inside stack.yml, which makes the YML more of a monstrosity than it already is.

    API网关的路由配置嵌入在stack.yml内的API网关(MyApiGateway)配置内,这使YML变得比以前更加stack.yml

  • Environment variables inside the HelloLambda Lambda configuration page contain the info needed to connect to the HelloTable DynamoDB table.

    HelloLambda Lambda配置页面中的环境变量包含连接到HelloTable DynamoDB表所需的信息。
  • The AWS-SDK comes bundled with every Lambda function so we can use require('aws-sdk') without a package.json. Very handy!

    AWS-SDK与每个Lambda函数捆绑在一起,因此我们可以在没有package.json情况下使用require('aws-sdk') 。 非常便利!

  • Instead of copying and pasting the NodeJS code into the embedded editor inside the Lambda Details page, you can deploy your code through the AWS CLI. We copy and paste for simplicity.

    您可以通过AWS CLI部署代码,而不是将NodeJS代码复制并粘贴到Lambda Details页面内的嵌入式编辑器中。 为了简单起见,我们复制并粘贴。
  • Be warned, the CloudFormation Stack Template is overwhelmingly verbose by nature. I promise it’s not just me and mystack.yml.

    请注意,CloudFormation堆栈模板本质上过于冗长。 我保证不仅仅是我和我的stack.yml

  • HelloTable DynamoDB table’s primary partition key is userId

    HelloTable DynamoDB表的主分区键为userId

  • From u/SalamiJack: “it’s worth calling out that API Gateway + Lambda performance, even for a warmed up, simple Lambda, is quite bad. Expect in the realm of 80–150ms response times at all times.”

    来自u / SalamiJack :“值得一提的是,即使对于一个简单的Lambda进行预热,API Gateway + Lambda的性能也是相当糟糕的。 始终期望在80-150ms的响应时间范围内。”

Originally published at medium.com on March 26, 2018.

最初于2018年3月26日发布在medium.com上。

翻译自: https://www.freecodecamp.org/news/quickly-create-a-serverless-restful-api-with-nodejs-and-aws-lambda-api-gateway-and-a6be891cc16a/

node aws 内存溢出

相关文章:

java学习之匿名内部类与包装类

匿名内部类: 所谓匿名内部类,顾名思义指的就是定义在类内部的匿名类,现有的spring框架开发以及java图形界面都经常用到匿名内部类。 下面来看一个代码: interface A{public void fun() ; } class B implements A{public void fun(…

【微信小程序】登录功能实现及讲解(获取用户唯一标识)

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 功能:登录实现并获取到用户唯一标识 官方文档地址:可以先看完我的文章再看官方地址 实现步骤:1.调用微信API wx.login()得到code 2.把得到的cod…

参考框架 系统 基准_带有基准的前端框架的真实比较(2018更新)

参考框架 系统 基准by Jacek Schae由Jacek Schae 带有基准的前端框架的真实比较(2018更新) (A Real-World Comparison of Front-End Frameworks with Benchmarks (2018 update)) This article is a refresh of A Real-World Comparison of Front-End Frameworks with Benchmar…

U盘重装MacOS-Sierra系统

Mac系统重新安装两种方法: 1、在线远程重装。 2、制作启动U盘进行重装。 理论上第一种比较简单,但是会比较耗时,实际操作中,由于网上下载的系统版本低于我现在MacOS的版本,导致无法安装,因此只能使用第二种…

this和that的区别和原理

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 本篇博文纯属个人见解,如有不妥,可以留言批评指正,谢谢。 var that this; this指的是当前的对象。 that是一个临时的变量,用于保存当…

linu逻辑分区动态调整大小

linu逻辑分区动态调整大小 注意: 这个动态调整的方法是有丢数据风险的,要确保调整的源分区没有使用或者使用率很低。源分区中如果有重要的文件最好先备份在centos 6.5上操作过lvdisplay 查看已有的分区的大小 lvdisplay ,选择要操作的逻辑分区&#…

多个敏捷团队同时做一个项目_您说您的团队很敏捷……但是这个词可能并不代表您的想法。...

多个敏捷团队同时做一个项目by Mark Shead由马克希德(Mark Shead) Many things get called Agile — especially by people who are selling something. But the Agile Manifesto makes it clear that it isn’t a methodology. It isn’t a specific way of doing software d…

Python IDLE theme

#转自 http://www.2cto.com/os/201507/418532.html #win10python3.5.2 #保护视力 .idlerc 目录下新建名为 config-highlight.cfg 文件,并加入如下内容 [tango] definition-foreground #fce94ferror-foreground #fa8072string-background #2e3436keyword-foregrou…

【转帖】SQLServer登录连接失败(error:40-无法打开到SQLServer的连接)的解决方案...

在与SQLServer建立连接时出现与网络相关的或特定与实例的错误.未找到或无法访问服务器.请验证实例名称是否正确并且SQL SERVER已配置允许远程链接.(provide:命名管道提供程序,error:40 -无法打开到SQL Server的连接)(Microsoft SQL Server,错误:2) 我刚刚在登录连接SQL Server …

js时间戳转换成日期格式

//时间戳转日期格式function timestampToTime(timestamp) {var date new Date(timestamp * 1000); //时间戳为10位需*1000&#xff0c;时间戳为13位的话不需乘1000Y date.getFullYear() -;M (date.getMonth() 1 < 10 ? 0 (date.getMonth() 1) : date.getMonth() 1)…

30岁找不到工作很绝望_计算机为绝望的新编码员工作方式的快速指南

30岁找不到工作很绝望by Danielle Ormshaw丹妮尔欧姆肖(Danielle Ormshaw) 计算机为绝望的新编码员工作方式的快速指南 (The quick guide to the way computers work for desperate new coders) The sole purpose of your computer is to send and receive information in the…

纯css3代码写下拉菜单效果

1 <!DOCTYPE html>2 <html lang"en">3 <head>4 <meta charset"UTF-8">5 <meta name"viewport" content"widthdevice-width,initial-scale1;user-scaleno">6 <title>CSS3树形菜单</title…

webpack chunkFilename 非入口文件的命名规则 [转]

官网的文档只理解了filename是主入口的文件名&#xff0c;chunkFilename是非主入口的文件名 filename应该比较好理解&#xff0c;就是对应于entry里面生成出来的文件名。比如&#xff1a; {entry: {"index": "pages/index.jsx"},output: {filename: "…

对数组中的数字从小到大排序

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 var arr [{name:1,age:1},{name:2,age:4},{name:3,age:2} ];function compare(e){return function(a,b){var value1 a[e];var value2 b[e];return value1 - value2;} } console.log(arr.sort(compare…

自动售货机编程_Rosmaro中基于视觉自动机的编程简介

自动售货机编程by Łukasz Makuch通过ŁukaszMakuch Rosmaro中基于视觉自动机的编程简介 (An introduction to visual automata-based programming in Rosmaro) To do automata-based programming is to program with states and transitions. States correspond to different…

JAVA设计模式之命令模式

将请求封装成一个对象&#xff0c;从而使你可以用不同的请求对客户进行参数化&#xff1b;对起那个请求进行排队或记录请求日志。 命令模式告诉我们可以为一个操作生成一个对象并给出它的一个execute(执行)方法。Command模式为系统架构带来效果&#xff1a; 实现请求一方&#…

vb.net与matlab的混合编程

首先,使用deploytool工具或者命令行将matlab的m文件编译成类,结果产生动态链接库.dll文件和一些c#代码的类. 第二步,将这些dll文件导入进去,并使用一些win32api函数,因为此m文件会产生figure窗口,这些api函数将此figure窗口嵌入到vb程序窗体里面. 代码: Imports SystemImports …

java web开发初学_2018年学习Web开发的绝对初学者指南

java web开发初学This post was originally published on Coder-Coder.com.该帖子最初发布在Coder-Coder.com上 。 If you’re a beginner coder, this guide is for you!如果您是初学者&#xff0c;那么本指南适合您&#xff01; Here is what this guide covers:本指南涵盖…

PC机安装android apk | adb install -r

PC 下载 *****.apk 通过adb直接安装到android系统 转载于:https://www.cnblogs.com/galoishelley/p/4353423.html

微信小程序之apply和call ( 附示例代码和注释讲解) apply call  bind

微信小程序开发交流qq群 173683895 相同点&#xff1a;作用是一样的&#xff0c;它们能劫持另外一个对象的方法&#xff0c;继承另外一个对象的属性&#xff1b; js中的call(), apply()和bind()是Function.prototype下的方法&#xff0c;都是用于改变函数运行时上下文&#…

(转)@ContextConfiguration注解说明

场景&#xff1a;学习spring实战中相关的单元测试 1 正常使用 ContextConfiguration Spring整合JUnit4测试时&#xff0c;使用注解引入多个配置文件 1.1 单个文件 ContextConfiguration(locations"../applicationContext.xml") ContextConfiguration(classes Simple…

ios pusher使用_如何使用JavaScript和Pusher构建实时评论功能

ios pusher使用by Rahat Khanna通过拉哈特汉娜 如何使用JavaScript和Pusher构建实时评论功能 (How to build a Live Comment feature using JavaScript and Pusher) These days “Social” has become the buzzword and we all want our apps to be the center of these amazi…

OpenDigg前端开源项目月报201704

由OpenDigg 出品的前端开源项目月报第一期来啦。我们的前端开源月报集合了OpenDigg一个月来新收录的优质前端开源项目&#xff0c;方便前端开发人员便捷的找到自己需要的项目工具。 reactide React web应用开发的第一个专用IDE redux-offline 持久性Redux存储 react-loadable 用…

ubuntu 14.04 使用apt-get出现如下问题解决办法

Some packages could not be installed. This may mean that you haverequested an impossible situation or if you are using the unstabledistribution that some required packages have not yet been createdor been moved out of Incoming. 使用aptitude这个代替apt-get …

java通用象棋游戏_在通用国际象棋界面周围模拟GraphQL包装器

java通用象棋游戏The Universal Chess Interface (UCI) has been around a long time and used by many chess engines. What does GraphQL bring to the mix?通用国际象棋界面(UCI)已经存在了很长时间&#xff0c;并且被许多国际象棋引擎使用。 GraphQL带来了什么&#xff1f…

表单高级应用和语义化

type"hidde" 隐藏域 disable 禁用 什么是表单语义化 符合W3C规范 语义化的标签 结构合理、代码简洁 分组<fieldset><legend>标题</legend> </fieldsrt> 关联<lable for"id"></lable>转载于:https://www.cnblogs.com/G…

modelsim中一个神奇又容易忽视的问题

最近在用modelsim对设计进行仿真的过程中发现了一个非常有趣的问题。接下来&#xff0c;让我们跟随着一个设计的仿真来发现问题的原因所在。首先&#xff0c;以调用基于IP核的加法器为例。加法器IP核的参数设置如下&#xff1a; 设计代码如下&#xff1a; /*******************…

html页面引入另一个html页面

微信小程序开发交流qq群 173683895 正文&#xff1a; 上源码&#xff1a; <!DOCTYPE html> <html><head><meta charset"utf-8" /><script src"js/jquery.js" type"text/javascript" charset"utf-8">…

javascript晚绑定_JavaScript的应用,调用和绑定通过托管野餐来解释

javascript晚绑定by Kevin Kononenko凯文科诺年科(Kevin Kononenko) JavaScript的应用&#xff0c;调用和绑定通过托管野餐来解释 (JavaScript’s apply, call, and bind explained by hosting a cookout) If you have ever been in charge of operating the grill at a famil…

13.angular时间

<!DOCTYPE html><html ng-app"myApp" ng-controller"myCtrl"><head lang"en"> <meta charset"UTF-8"> <title>T38-angular时间</title> <script src"js/angular.js" type&…