java - 如何减少代码中的 Lambda 冷启动时间?
问题描述
我正在为移动应用程序开发 REST API。该移动应用程序预计将拥有数百万用户,并且每天都在使用。
我正在为此使用AWS Lambda
, API Gateway
,Amazon RDS (MySQL)
技术。此外,我正在使用该CloudFormation
文件来配置所有内容。
我注意到这里的每个函数都有3 seconds 到 3.8 seconds的冷启动时间。这需要尽可能地减少。
HikariCPDataSource
import java.sql.Connection;
import java.sql.SQLException;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
public class HikariCPDataSource {
private static HikariConfig config = new HikariConfig();
private static HikariDataSource ds;
static {
config.setJdbcUrl("jdbc:mysql://gfgf.ffgfg.us-east-1.rds.amazonaws.com:3306/aaaa");
config.setUsername("admin");
config.setPassword("admin123");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
ds = new HikariDataSource(config);
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
private HikariCPDataSource(){}
}
GetAllAccountTypesLambda
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.peresiaapp.beans.AccountingType;
import java.util.ArrayList;
import java.util.List;
import java.sql.*;
public class GetAllAccountTypesLambda {
ObjectMapper objectMapper = new ObjectMapper();
static final String QUERY = "SELECT * from accounting_type";
static Connection conn = null;
static {
try {
conn = HikariCPDataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
public APIGatewayProxyResponseEvent getAllAccountTypes(APIGatewayProxyResponseEvent request)
throws JsonProcessingException, ClassNotFoundException {
List<AccountingType> list = new ArrayList<>();
AccountingType acc = new AccountingType();
try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(QUERY);) {
// Extract data from result set
while (rs.next()) {
// Retrieve by column name
acc.setIdaccountingType(rs.getInt("idaccounting_Type"));
acc.setType(rs.getString("type"));
list.add(acc);
}
} catch (SQLException e) {
e.printStackTrace();
}
String writeValueAsString = objectMapper.writeValueAsString(list);
return new APIGatewayProxyResponseEvent().withStatusCode(200).withBody(writeValueAsString);
}
}
模板.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
aaaa-restapi
Sample SAM Template for aaaa-restapi
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 100
Resources:
GetAllAccountTypesLambda:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: aaaa-restapi
Handler: com.peresiaapp.dao.accountingtype.GetAllAccountTypesLambda::getAllAccountTypes
Runtime: java11
MemorySize: 1024
Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
Variables:
PARAM1: VALUE
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /accounttype
Method: get
Role: !GetAtt LambdaRole.Arn
VpcConfig:
SecurityGroupIds:
- sg-041f2459dcd921e8e
SubnetIds:
- subnet-0381dfdfd
- subnet-c4ddf54cb
GetAllRolesLambda:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: aaaa-restapi
Handler: com.peresiaapp.dao.accountingtype.GetAllRolesLambda::getAllRoles
Runtime: java11
MemorySize: 1024
Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
Variables:
PARAM1: VALUE
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /roles
Method: get
Role: !GetAtt LambdaRole.Arn
VpcConfig:
SecurityGroupIds:
- sg-041f2459dcd921e8e
SubnetIds:
- subnet-0381sds2d
- subnet-c4d5sdsb
LambdaRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: root
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- ec2:DescribeNetworkInterfaces
- ec2:CreateNetworkInterface
- ec2:DeleteNetworkInterface
- ec2:DescribeInstances
- ec2:AttachNetworkInterface
Resource: '*'
*更新
有几条评论建议我使用预置并发。我确实尝试过。没看出有太大区别。但是,如果你们中的任何人都可以解释低于900的情况,那就太好了。我有数百个函数,这是否也意味着我打开并发必须花费大量资金?因为pricing
页面中的数字似乎不同,这对我来说没问题 - https://aws.amazon.com/lambda/pricing/
解决方案
推荐阅读
- android - 材质库中的 Theme.MaterialComponents.Light 主题已损坏?
- c++ - 无法理解 Robert Martin 的 ISP 文章中的“矛盾”
- linux - 在 cron 作业中一次复制一个文件的 Shell 脚本
- docker - 是否可以从 Linux 上的 docker 容器中重新启动计算机?
- java - 如何让私人成员遵守亲守规则
- javascript - Appium:在 MAC OS 中处理命令时发生未知的服务器端错误
- android - 我的项目在构建变体文件夹中找不到 google-services.json
- typescript - 用打字稿键入 jest test.each 标记的模板文字
- c# - 如果当前行抛出异常,如何执行下一行代码
- javascript - typeahead 设置数组键值对