【问题标题】:Initializing DynamoDB Instance has a bad performance初始化 DynamoDB 实例性能不佳
【发布时间】:2022-07-15 22:03:14
【问题描述】:
我正在使用 .Net Core 3.1 开发 Lambda 函数,并尝试使用高级 API 来操作 DynamoDB。
var db = new AmazonDynamoDBClient(); // this takes over 2000 ms
var table = Table.LoadTable(db, "my-table"); // this takes over 1500 ms
这看起来是一个非常糟糕的表现,但我不知道如何改进它。 Lambda 函数部署在同一 AWS 账户下的同一区域。
【问题讨论】:
标签:
amazon-web-services
.net-core
aws-lambda
amazon-dynamodb
【解决方案1】:
您使用的是哪个版本的 SDK?
发生这种情况是因为 DynamoDBClient 在首次初始化时需要与 AWS 执行 TLS 握手。这会对性能产生一些影响。不过,作为最佳实践,您可以在函数处理程序之外执行此操作。如果您在函数构造函数中初始化了 DynamoDbClient 和 Table,则此 DynamoDB 初始化将发生一次,然后该环境中的每个后续调用都将重用同一对象。
类似这样的:
public class Function
{
private readonly AmazonDynamoDBClient _client;
public Function()
{
this._client = new AmazonDynamoDBClient();
}
public async Task<APIGatewayHttpApiV2ProxyResponse> FunctionHandler(APIGatewayHttpApiV2ProxyRequest apigProxyEvent,
ILambdaContext context)
{
if (!apigProxyEvent.RequestContext.Http.Method.Equals(HttpMethod.Get.Method))
{
return new APIGatewayHttpApiV2ProxyResponse
{
Body = "Only GET allowed",
StatusCode = (int)HttpStatusCode.MethodNotAllowed,
};
}
try
{
// Use your _client here
return new APIGatewayHttpApiV2ProxyResponse
{
StatusCode = (int)HttpStatusCode.OK,
Body = JsonSerializer.Serialize(product),
Headers = new Dictionary<string, string> {{"Content-Type", "application/json"}}
};
}
catch (Exception e)
{
context.Logger.LogLine($"Error getting product {e.Message} {e.StackTrace}");
return new APIGatewayHttpApiV2ProxyResponse
{
Body = "Not Found",
StatusCode = (int)HttpStatusCode.InternalServerError,
};
}
}
}