aws lambda_如何通过在本地模拟AWS Lambda来加速无服务器开发

aws lambda

by John McKim

约翰·麦金(John McKim)

如何通过在本地模拟AWS Lambda来加速无服务器开发 (How you can speed up serverless development by simulating AWS Lambda locally)

Designing AWS Lambda functions can be a frustrating experience. Each time you make a change, you have to deploy your code to AWS before you can test it. Well, my friend and I finally decided to do something about this.

设计AWS Lambda函数可能会令人沮丧。 每次进行更改时,都必须先将代码部署到AWS,然后才能对其进行测试。 好吧, 我的朋友终于决定对此做些事情。

The end result is the Serverless Simulate Plugin. This plugin is an AWS Lambda and API Gateway simulator for the Serverless Framework.

最终结果是无服务器模拟插件 。 该插件是用于无服务器框架的AWS Lambda和API网关模拟器。

I’m going to walk you through how we built this and how you can start using it when you develop serverless apps.

我将向您介绍我们如何构建它以及如何在开发无服务器应用程序时开始使用它。

模拟API网关 (Simulating API Gateway)

API Gateway provides HTTP endpoints that invoke Lambda functions in response to requests.

API网关提供HTTP终结点,以响应请求来调用Lambda函数。

API Gateway maps the incoming HTTP request to an event payload for Lambda. When the Lambda function returns a result, the result is mapped to a HTTP response.

API网关将传入的HTTP请求映射到Lambda的事件有效负载。 当Lambda函数返回结果时,该结果将映射到HTTP响应。

While API Gateway has a lot of features, most developers only use a few of them. We chose to only implement the features commonly used by Serverless developers.

虽然API Gateway具有许多功能,但大多数开发人员仅使用其中的一些功能。 我们选择仅实现无服务器开发人员常用的功能。

HTTP服务器 (HTTP Server)

To simulate API Gateway the plugin creates a HTTP server with express. The plugin reads the Serverless config file and creates endpoints from the HTTP events.

为了模拟API Gateway,该插件使用express创建一个HTTP服务器。 该插件读取Serverless配置文件,并根据HTTP事件创建端点。

If the endpoint has enabled CORS, the plugin will add CORS Middleware to the endpoint.

如果端点已启用CORS,则插件会将CORS中间件添加到端点。

定制授权人 (Custom Authorizers)

API Gateway can Authorize endpoints in a few different ways. A common approach is to use a Custom Authorizer.

API网关可以通过几种不同的方式授权端点。 一种常见的方法是使用自定义授权器

To simulate Custom Authorizers, we created an express js middleware function. The middleware creates the Lambda event with authorization information from the request. The Authorizer function is then invoked locally.

为了模拟自定义授权者,我们创建了一个快速的js中间件功能。 中间件使用来自请求的授权信息创建Lambda事件。 然后在本地调用Authorizer函数。

Custom Authorizers allow or deny requests based on a policy document. The middleware reads the policy document returned by the Authorizer. If the request is not allowed to access an endpoint, the middleware will return an Unauthorized response.

定制授权者基于策略文档允许或拒绝请求。 中间件读取授权者返回的策略文档。 如果不允许该请求访问端点,则中间件将返回未经授权的响应。

Lambda整合 (Lambda Integration)

API Gateway has two integrations with AWS Lambda. The original Lambda integration and the newer Lambda Proxy.

API Gateway与AWS Lambda有两个集成。 原始的Lambda集成和更新的Lambda代理

Both integrations map HTTP requests to a Lambda event. When Lambda returns a result, the integration maps the result to a HTTP response.

两种集成都将HTTP请求映射到Lambda事件。 当Lambda返回结果时,集成会将结果映射到HTTP响应。

We developed two mapping functions that mimic Lambda and Lambda Proxy. The server selects the integration based on the HTTP event configuration in serverless.yml.

我们开发了两个模仿Lambda和Lambda Proxy的映射功能。 服务器根据serverless.yml的HTTP事件配置选择集成。

When a request is received, the server performs the same mapping process as API Gateway. A simplified version of the code is below.

收到请求后,服务器将执行与API网关相同的映射过程。 下面是该代码的简化版本。

function(req, res) {  integration.event(req)    .then(event => lambda.invoke(context, event))    .then(result => integration.response(req, result))    .then(response => respond(res, response))}

The end result is an express server that behaves like API Gateway.

最终结果是表现得像API网关的Express服务器。

使用API​​网关模拟器 (Using the API Gateway Simulator)

To use the API Gateway simulator you need to install the plugin into your Serverless project. Please read the docs for instructions.

要使用API​​网关模拟器,您需要将插件安装到无服务器项目中。 请阅读文档以获取说明。

To start the API Gateway simulator run the following command:

要启动API网关模拟器,请运行以下命令:

sls simulate apigateway -p 5000

sls simulate apigateway -p 5000

This will start a HTTP server that you can use to test your endpoints and functions locally.

这将启动HTTP服务器,您可以使用该服务器在本地测试端点和功能。

The API Gateway simulation is similar to other offline plugins for the Serverless Framework. The real difference with Serverless Simulate is how we simulate Lambda locally.

API Gateway模拟类似于Serverless Framework的其他脱机插件。 无服务器模拟的真正区别在于我们如何在本地模拟Lambda。

模拟AWS Lambda (Simulating AWS Lambda)

AWS Lambda is powered by a HTTP API. Functions are invoked through a HTTP request to the Lambda API.

AWS Lambda由HTTP API驱动。 通过对Lambda API的HTTP请求调用函数。

When the Invoke API is called, the Lambda service runs your code inside a container. For more details see the docs.

调用Invoke API时,Lambda服务在容器内运行您的代码。 有关更多详细信息,请参阅文档

While AWS Lambda is a complex service, the core elements are reasonably easy to simulate. To simulate it locally we implemented three services, function runtimes, a function registry and HTTP API.

尽管AWS Lambda是一项复杂的服务,但其核心元素相当容易模拟。 为了在本地模拟它,我们实现了三个服务,函数运行时,函数注册表和HTTP API。

函数运行时 (Function Runtimes)

We use a Docker image created by Michael Hart to create the function runtime. Using Docker allows us to control the environment and enforce memory limits and timeouts.

我们使用由Michael Hart创建的Docker映像来创建函数运行时。 使用Docker可让我们控制环境并强制执行内存限制和超时。

功能注册表 (Function Registry)

The Function Registry is a local JSON database powered by lowdb. The registry stores information about the function configuration and location.

Function Registry是一个由lowdb支持的本地JSON数据库。 注册表存储有关功能配置和位置的信息。

This allows the server to lookup the details of a function when a request is received by the API.

当API收到请求时,这允许服务器查找功能的详细信息。

HTTP API (HTTP API)

The HTTP API provides a registration endpoint for clients. The registration endpoint is used by the plugin to register functions.

HTTP API为客户端提供注册端点。 插件使用注册端点来注册功能。

The HTTP API also provides an endpoint to invoke functions. The invoke endpoint mimics the AWS Lambda API. This allows clients to use an AWS SDK to invoke functions.

HTTP API还提供了一个调用函数的端点。 调用端点模仿AWS Lambda API。 这允许客户端使用AWS开发工具包调用功能。

为什么使用Lambda Simulator (Why use the Lambda Simulator)

The Lambda simulator allows you to invoke Lambda functions locally from other services. That might include another Lambda function in a different Serverless service. Or it could include a completely different application.

Lambda模拟器允许您从其他服务本地调用Lambda函数。 这可能在其他无服务器服务中包括另一个Lambda函数。 或者它可能包含一个完全不同的应用程序。

This is useful if you are chaining Lambda functions or migrating an existing application to AWS Lambda.

如果您要链接Lambda函数或将现有应用程序迁移到AWS Lambda,这将很有用。

For example, this function invokes another Lambda function locally. Without the Lambda Simulator, the second function would be invoked in AWS.

例如,此函数在本地调用另一个Lambda函数。 如果没有Lambda Simulator,则第二个函数将在AWS中调用。

// If offline use the local registryconst endpoint = process.env.SERVERLESS_SIMULATE ?  process.env.SERVERLESS_SIMULATE_LAMBDA_ENDPOINT :  undefined
// configure the AWS SDK to use the local endpointconst lambda = new AWS.Lambda({ endpoint })
const handler = (event, context, callback) => {  const params = {    FunctionName: 'my-other-function',    Payload: JSON.stringify({ foo: 'bar' })  }
lambda.invoke(params, (err, result) => {    if (err) {      return callback(err)    }        callback(null, {      statusCode: 200,      body: result.Payload    })    })}
使用Lambda模拟器 (Using the Lambda Simulator)

To use the Lambda simulator you need to install the plugin into your Serverless project. Please read the docs for instructions.

要使用Lambda模拟器,您需要将插件安装到无服务器项目中。 请阅读文档以获取说明。

To start the Lambda simulator run the following command:

要启动Lambda模拟器,请运行以下命令:

sls simulate lambda -p 4000

sls simulate lambda -p 4000

To use the Lambda Simulator with the API Gateway, run the API Gateway command with --lambda-port argument.

要将Lambda Simulator与API网关一起使用,请运行带有--lambda-port参数的API Gateway命令。

sls simulate apigateway -p 5000 --lambda-port

sls simulate apigateway -p 5000 --lambda-port

When using the --lambda-port argument, the API Gateway simulator invokes functions via the HTTP API.

使用--lambda-port参数时,API网关模拟器会通过HTTP API调用函数。

This allows you to simulate complex architectures locally before deploying to the cloud.

这使您可以在部署到云之前在本地模拟复杂的体系结构。

与其他插件的比较 (Comparison to Other Plugins)

Serverless Offline is the most popular plugin for the Serverless Framework. Unfortunately, the design of Serverless Offline limits the quality of the simulation.

Serverless Offline是Serverless Framework最受欢迎的插件。 不幸的是,无服务器脱机的设计限制了仿真的质量。

This plugin simulates API Gateway and executes functions in the plugin process. The downsides of this decision include:

该插件模拟API网关并在插件过程中执行功能。 该决定的缺点包括:

  • No Python support

    不支援Python
  • It uses whatever NodeJS version you are running, which may not be the same NodeJS version as AWS Lambda

    它使用您正在运行的任何NodeJS版本,该版本可能与AWS Lambda不同。
  • It does not enforce memory limits or timeouts

    它不强制执行内存限制或超时
  • There is no way to chain Lambda function calls

    无法链接Lambda函数调用

We designed Serverless Simulate to solve these problems.

我们设计了无服务器模拟来解决这些问题。

继续建造 (Go forth and build)

This plugin will help solve a big problem for myself and the team at A Cloud Guru. Unit tests and local executions reduce the time we spend waiting for deployments to the cloud.

该插件将帮助我自己和A Cloud Guru团队解决一个大问题。 单元测试和本地执行减少了我们花费在等待部署到云上的时间。

The Serverless Framework and Serverless Simulate are both Open Source projects. If you want to get involved, you can help by creating issues or submitting a pull request.

无服务器框架和无服务器模拟都是开源项目。 如果您想参与其中,可以通过创建问题或提交拉取请求来提供帮助。

I hope that it will help you save time when you are testing Lambda functions locally.

我希望它可以帮助您在本地测试Lambda函数时节省时间。

If you have any questions about this project or Serverless in general you can contact me on Medium or Twitter. I’ll be running a workshop at ServerlessConf Austin if you want to meet me in person.

如果您对此项目或一般无服务器有任何疑问,可以通过Medium或Twitter与我联系。 如果您想亲自见我,我将在ServerlessConf Austin举办一个研讨会。

翻译自: https://www.freecodecamp.org/news/how-you-can-speed-up-serverless-development-by-simulating-aws-lambda-locally-41c61a60fbae/

aws lambda

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值