gpt4 book ai didi

java - 如何减少代码中的 Lambda 冷启动时间?

转载 作者:行者123 更新时间:2023-12-03 07:16:31 27 4
gpt4 key购买 nike

我正在为移动应用程序开发 REST API。该移动应用程序预计将拥有数百万用户,并且每天都会使用。

我为此使用 AWS LambdaAPI GatewayAmazon RDS (MySQL) 技术。此外,我使用 CloudFormation 文件来配置所有内容。

我注意到这里的每个功能都有一个3秒到3.8秒的冷启动时间。这需要尽可能减少。

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 个可用,那就太好了。我有数百个功能,这是否也意味着如果我开启并发就必须花费大量资金?因为定价页面中的数字似乎有所不同,这对我来说没问题 - https://aws.amazon.com/lambda/pricing/

enter image description here

最佳答案

关于java - 如何减少代码中的 Lambda 冷启动时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68436098/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com