node.js - 为什么一个简单的 SQL 查询会导致我的 Lambda 函数显着变慢?
问题描述
我构建了一个托管在 AWS Lambda 上并通过 AWS API Gateway 提供服务的基本 node.js API。这是代码:
'use strict';
// Require and initialize outside of your main handler
const mysql = require('serverless-mysql')({
config: {
host : process.env.ENDPOINT,
database : process.env.DATABASE,
user : process.env.USERNAME,
password : process.env.PASSWORD
}
});
// Import the Dialogflow module from the Actions on Google client library.
const {dialogflow} = require('actions-on-google');
// Instantiate the Dialogflow client.
const app = dialogflow({debug: true});
// Handle the Dialogflow intent named 'trip name'.
// The intent collects a parameter named 'tripName'.
app.intent('trip name', async (conv, {tripName}) => {
// Run your query
let results = await mysql.query('SELECT * FROM tablename where field = ? limit 1', tripName)
// Respond with the user's lucky number and end the conversation.
conv.close('Your lucky number is ' + results[0].id);
// Run clean up function
await mysql.end()
});
// Set the DialogflowApp object to handle the HTTPS POST request.
exports.fulfillment = app;
它接收一个参数(行程名称),在 MySQL 中查找并返回结果。
我的问题是 API 响应时间超过 5 秒,速度很慢。
我不知道为什么它很慢?MySQL 是一个强大的Amazon Aurora,并且 node.js 应该很快。
我从与 MySQL(孟买)相同的 AWS 区域测试了该功能,但它仍然超时,所以我认为它与不同区域之间的距离无关。
缓慢的原因是执行任何 SQL 查询(甚至是非常简单的SELECT
)。它确实带回了正确的结果,但速度很慢。
当我删除 SQL 部分时,它变得非常快。我将 Lambda 的内存增加到最大,并将 Aurora 重新部署到更强大的内存。
解决方案
如果您配置更多内存,Lambda 函数将运行得更快。配置的内存越少,性能越差。
这意味着如果您已将函数配置为使用 128MB,它将在非常低配置的硬件中运行。
另一方面,如果您将其配置为使用 3GB,它将在一台非常不错的机器上运行。
在 1792MB 时,您的函数将在具有专用内核的硬件中运行,考虑到您正在使用 IO 调用(例如网络请求),这将显着加快您的代码速度。您可以在此处查看此信息
虽然没有神奇的公式。您必须运行一些测试并查看最适合您的应用程序的内存配置。我会从 3GB 开始,最终减少 128MB 的块,直到找到正确的配置。
推荐阅读
- angular - “Renderer2”类型上不存在属性“projectNodes”
- android - Android KeyEvent.getCharacters() 或 keyEvent.characters 已弃用
- java - 如何从用 Java 编写的 Azure Function App 连接到 PostgreSQL?
- sql - Oracle中的正则表达式-每5个字符后放置一个字符串
- javascript - TypeError:class.function 不是函数。(在 'classname.function(param)' 中)
- php - 基本匿名用户评级系统 - 不工作
- asp.net-core-mvc - Blazor Hub 未跨整个 MVC 应用程序连接
- sql-server - 将 DTS 变量传递给带有 DTEXEC 的 SSIS 2008 包
- asp.net-core - 在 .Net core 3 和 blazor 中捆绑 css 和 js
- javascript - RXJS RetryWhen - 在尝试重试时继续下游错误