aws lambda_Express.js和AWS Lambda —无服务器的爱情故事

aws lambda

by Slobodan Stojanović

由SlobodanStojanović

Express.js和AWS Lambda —无服务器的爱情故事 (Express.js and AWS Lambda — a serverless love story)

If you are a Node.js developer or you’ve built an API with Node.js, there’s a big chance you used Express.js. Express is de facto the most popular Node.js framework.

如果您是Node.js开发人员,或者已经使用Node.js构建了API,那么使用Express.js的机会很大。 Express 实际上是最受欢迎的Node.js框架。

Express apps are easy to build. For a simple app, you just need to add a few routes and route handlers. That’s it.

Express应用程序易于构建。 对于一个简单的应用程序,您只需要添加一些路由和路由处理程序即可。 而已。

For example, the simplest Express app looks like the following code snippet:

例如,最简单的Express应用程序看起来像以下代码片段:

'use strict'
const express = require('express')const app = express()
app.get('/', (req, res) => res.send('Hello world!'))
const port = process.env.PORT || 3000app.listen(port, () =>   console.log(`Server is listening on port ${port}.`))

If you save that code snippet as app.js in a new folder, you are just three steps away from having a simple Express app:

如果将该代码段另存为app.js到新文件夹中,那么距离拥有一个简单的Express应用程序仅三步之遥:

  1. Create a new Node.js project. To do so, run the npm init -y command in your terminal. Just make sure you navigated to the folder that contains app.js first.

    创建一个新的Node.js项目。 为此,请在终端中运行npm init -y命令。 只要确保您先导航到包含app.js的文件夹即可。

  2. Install the Express module from NPM by running the npm install express --save command from terminal.

    通过从终端运行npm install express --save命令,从NPM安装Express模块​​。

  3. Run the node app.js command, and you should see “Server is listening on port 3000.” as a response.

    运行node app.js命令,您应该看到“服务器正在侦听端口3000”。 作为回应。

Voila! You have an Express app. Visit http://localhost:3000 in your browser, and you’ll see a “Hello world!” message.

瞧! 您有一个Express应用。 在浏览器中访问http:// localhost:3000,您将看到一个“ Hello world!” 信息。

应用部署 (Application deployment)

Now comes the hard part: How can you show it to your friends or family? How to make it available for everyone?

现在来了困难的部分:如何将其展示给您的朋友或家人? 如何使所有人都能使用?

Deployment can be long and painful process, but let’s imagine you manage to do it quickly and successfully. Your app is available to everyone and it lived happily ever after.

部署可能是一个漫长而痛苦的过程,但让我们想象一下您可以成功快速地完成部署。 您的应用可供所有人使用,并且从此幸福快乐地生活着。

Until one day, an unexpected army of users started using it.

直到一天,大量的用户开始使用它。

Your server struggled, but it worked.

您的服务器很挣扎,但是可以正常工作。

At least for some time. And then it died. ☠️

至少一段时间。 然后它死了。 ☠️

An army of users is angry (at least they didn’t pay for the app — or did they?) You are desperate and trying to Google the solution. Can the cloud help?

一大群用户很生气(至少他们没有为应用程序付费-还是他们?)。您很拼命,尝试使用Google解决方案。 云可以帮助吗?

And you’ve met one of your annoying friends again. She’s talking about that serverless thingy again. But come on, you still have a server. It just belongs to somebody else and you have no control over it.

而且您又遇到了一个令人讨厌的朋友。 她又在谈论无服务器的问题。 但是,来吧,您仍然有一台服务器。 它只是属于其他人,您无法控制它。

But you are desperate, you would try anything, including black magic and even serverless. “What the heck is that serverless thingy, anyway?”

但是您绝望了,您会尝试任何东西,包括黑魔法,甚至是无服务器的。 “不管怎么说,无服务器到底是什么鬼东西?”

You ended up with many links, including the one to the free first chapter of “Serverless Applications with Node.js” by Manning Publications.

您最终获得了许多链接,其中包括Manning Publications的免费第一章 “带有Node.js的无服务器应用程序”。

That chapter explains serverless with washing machines!? Sounds crazy, but it kinda makes sense. ? already hit the fan, so you decide to try it.

该章介绍了无服务器洗衣机!? 听起来很疯狂,但这很有道理。 ? 已经打了迷,所以您决定尝试一下。

使您的Express.js应用变为无服务器 (Making your Express.js app serverless)

That chapter was all about serverless on AWS. And now you know that Serverless API consists of an API Gateway and AWS Lambda functions. But how can you go serverless with your Express app?

该章都是关于AWS上的无服务器的。 现在,您知道无服务器API由API网关和AWS Lambda函数组成。 但是如何使用Express应用程序实现无服务器化呢?

This sounds as promising as that movie about Matt Damon shrinking…

这听起来像那部关于马特·达蒙(Matt Damon)缩水的电影一样有希望……

Claudia could help you to deploy your app to AWS Lambda — lets ask her for help!

Claudia可以帮助您将应用程序部署到AWS Lambda –让她寻求帮助!

Make sure you configured your AWS access credentials as explained in this tutorial before running Claudia commands.

在运行Claudia命令之前,请确保已按照本教程中的说明配置了AWS访问凭证。

Your code should be slightly modified to support AWS Lambda and deployment via Claudia. You need to export your app instead of starting the server using app.listen. Your app.js should look like the following code listing:

您的代码应稍作修改以支持AWS Lambda并通过Claudia进行部署。 您需要导出app而不是使用app.listen启动服务器。 您的app.js应该类似于以下代码清单:

'use strict'
const express = require('express')const app = express()
app.get('/', (req, res) => res.send('Hello world!'))
module.exports = app

That would break a local Express server, but you can add app.local.js file with the following content:

那会破坏本地Express服务器,但是您可以添加具有以下内容的app.local.js文件:

'use strict'
const app = require('./app')
const port = process.env.PORT || 3000app.listen(port, () =>   console.log(`Server is listening on port ${port}.`))

And then run the local server using the following command:

然后使用以下命令运行本地服务器:

node app.local.js

To make your app work correctly with AWS Lambda, you need to generate AWS Lambda wrapper for your Express app. With Claudia, you can do so by running the following command in your terminal:

为了使您的应用程序可以与AWS Lambda一起正常工作,您需要为Express应用程序生成AWS Lambda包装器。 使用Claudia,您可以通过在终端中运行以下命令来实现:

claudia generate-serverless-express-proxy --express-module app

where app is a name of an entry file of your Express app, just without the .js extension.

其中app是Express应用程序条目文件的名称,只是不带.js扩展名。

This step generated a file named lambda.js, with the following content:

此步骤生成了一个名为lambda.js的文件,其内容如下:

'use strict'const awsServerlessExpress = require('aws-serverless-express')const app = require('./app')const binaryMimeTypes = [  'application/octet-stream',  'font/eot',  'font/opentype',  'font/otf',  'image/jpeg',  'image/png',  'image/svg+xml']const server = awsServerlessExpress  .createServer(app, null, binaryMimeTypes)exports.handler = (event, context) =>  awsServerlessExpress.proxy(server, event, context)

That’s it! Now you only need to deploy your Express app (with lambda.js file) to AWS Lambda and API Gateway using the claudia create command.

而已! 现在,您只需要使用claudia create命令将Express应用程序(带有lambda.js文件)部署到AWS Lambda和API Gateway。

claudia create --handler lambda.handler --deploy-proxy-api --region eu-central-1

After a few moments, the command finished and printed the following response:

片刻之后,该命令完成并打印以下响应:

{  "lambda": {    "role": "awesome-serverless-expressjs-app-executor",    "name": "awesome-serverless-expressjs-app",    "region": "eu-central-1"  },  "api": {    "id": "iltfb5bke3",    "url": "https://iltfb5bke3.execute-api.eu-central-1.amazonaws.com/latest"  }}

And if you visit the link from that response in your browser, it prints “Hello world!” It worked! ?

而且,如果您在浏览器中访问该响应中的链接,则会显示“ Hello world!”。 有效! ?

With a serverless app, your army of users can continue growing and your app will still be working.

借助无服务器应用程序,您的用户群可以继续增长,并且您的应用程序仍将正常运行。

It is possible, because AWS Lambda will auto scale up to 1000 concurrent executions by default. New functions are ready a few moments after the API Gateway receives the request.

这是有可能的,因为默认情况下,AWS Lambda会自动扩展至1000个并发执行。 API网关收到请求后不久,新功能便准备就绪。

But this is not your only benefit. You also saved money besides having a stable app under a higher load. With AWS Lambda, you pay only for requests you used. Also, the first million requests each month are free, as part of a free tier.

但这不是您唯一的好处。 除了在更高负载下拥有稳定的应用程序之外,您还节省了资金。 使用AWS Lambda,您只需为您使用的请求付费。 此外,作为免费套餐的一部分,每月前100万个请求是免费的。

To read more about the ways your business benefits through serverless, see this article.

要通过无服务器阅读更多关于如何您的企业的利益,看到这个文章。

无服务器Express.js应用程序的局限性 (Limitations of serverless Express.js apps)

Serverless Express apps sound awesome, but they have some limitations.

无服务器Express应用程序听起来很棒,但是它们有一些限制。

Some of the important limitations of serverless Express apps are the following:

无服务器Express应用程序的一些重要限制如下:

  • Websockets don’t work with AWS Lambda. That’s because your server doesn’t exist when there are no requests. Some limited support for websockets is available through AWS IOT websockets over MQTT protocol.

    Websockets不适用于AWS Lambda。 这是因为没有请求时您的服务器不存在。 通过MQTT协议的AWS IOT Websockets可提供对Websockets的某些有限支持。

  • Upload to the file system will not work either, unless you are uploading to the /tmp folder. That’s because the AWS Lambda function is read-only. Even if you upload files to /tmp folder, they will exist for a short time, while the function is still “warm”. To make sure your upload feature is working fine, you should upload files to AWS S3.

    除非您要上传到/tmp文件夹,否则上传到文件系统也将不起作用。 那是因为AWS Lambda函数是只读的。 即使您将文件上传到/tmp文件夹,它们也会存在很短的时间,而该功能仍然是“暖和的”。 为了确保您的上传功能正常运行,您应该将文件上传到AWS S3。

  • Execution limits can also affect your serverless Express app. Because API Gateway has a timeout of 30 seconds, and AWS Lambda’s maximum execution time is 5 minutes.

    执行限制也会影响您的无服务器Express应用程序。 因为API Gateway的超时时间为30秒,并且AWS Lambda的最大执行时间为5分钟。

This is just a beginning of a serverless love story between your apps and AWS Lambda. Expect more stories soon!

这只是您的应用程序与AWS Lambda之间无服务器爱情故事的开始。 期待更多故事!

As always, many thanks to my friends Aleksandar Simović and Milovan Jovičić for help and feeback on the article.

一如既往,非常感谢我的朋友AleksandarSimovićMilovanJovičić对本文的帮助和反馈。

All illustrations are created using SimpleDiagrams4 app.

所有插图都是使用SimpleDiagrams4应用程序创建的。

If you want to learn more about serverless Express and serverless apps in general, check out “Serverless Applications with Node.js”, the book I wrote with Aleksandar Simovic for Manning Publications:

如果您想大致了解有关无服务器Express和无服务器应用程序的更多信息,请查看我与Aleksandar Simovic为Manning Publications撰写的书“带有Node.js的无服务器应用程序”:

Serverless Applications with Node.jsA compelling introduction to serverless deployments using Claudia.js.www.manning.com

带有Node.js 无服务器应用程序有关 使用Claudia.js的无服务器部署的引人注目的介绍。 www.manning.com

The book will teach you more about serverless Express apps, but you’ll also learn how to build and debug a real world serverless API (with DB and authentication) using Node and Claudia.js. And how to build chatbots, for Facebook Messenger and SMS (using Twilio), and Alexa skills.

该书将教您更多有关无服务器Express应用程序的信息,但您还将学习如何使用Node和Claudia.js构建和调试真实的无服务器API(具有数据库和身份验证)。 以及如何为Facebook Messenger和SMS(使用Twilio)以及Alexa技能构建聊天机器人。

翻译自: https://www.freecodecamp.org/news/express-js-and-aws-lambda-a-serverless-love-story-7c77ba0eaa35/

aws lambda

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值