如何减少aws lambda函数nodejs的执行时间

问题描述 投票:0回答:1

我在 aws sam lambda 函数节点 x20 中编写了一个 api。
这个 api 负责登录用户并向我返回响应。
冷启动时看起来需要 6 秒,之后需要 3 秒(平均)才能返回响应。

我想要什么?我想要的是,返回响应的时间应该小于2秒。我能做什么。

export const loginHandler = catchTryAsyncErrors(async (event) => {
  const headers = generateCorsHeaders();
  const DB = await DBConn();

  const requestBody = JSON.parse(event.body);
  await loginValidation.validate(requestBody, { abortEarly: false });
  const { password, email, platform = "CLIENT" } = requestBody;

  let response, error;
  const user = await DB.collection("users").findOne({
    email: email.toLowerCase(),
    isAccCreated: true,
    role: platform === "CLIENT" ? "Client" : "Admin",
  });

  if (!user) {
    error = new HTTPError("The email address was not found.", StatusCodes.NOT_FOUND);
    return {
      statusCode: StatusCodes.NOT_FOUND,
      headers,
      body: JSON.stringify(error),
    };
  }

  const passwordMatch = await bcryptjs.compare(password, user.password);
  if (!passwordMatch) {
    error = new HTTPError("The password entered is incorrect.", StatusCodes.CONFLICT);
    return {
      statusCode: StatusCodes.CONFLICT,
      headers,
      body: JSON.stringify(error),
    };
  }
  user.password = undefined;

  if (user["status"] === "Blocked") {
    error = new HTTPError("This user account has been blocked by the administrator.", StatusCodes.CONFLICT);
    return {
      statusCode: StatusCodes.CONFLICT,
      headers,
      body: JSON.stringify(error),
    };
  }

  if (user.role === "Admin") {
    const logData = {
      ip: event?.requestContext?.identity?.sourceIp,
      user: new ObjectId(user?._id),
      activity: "ADMIN_LOGIN",
      msg: `${user?.userName} login into Admin Site`,
      createdAt: new Date(),
      updatedAt: new Date(),
    };
    await DB.collection("logs").insertOne(logData);
  }

  const token = await getJWTToken({ _id: user["_id"], role: user["role"] });
  // const userWallet = await DB.collection("userwallets").findOne({
  //   _id: user?.userWallet,
  // });

  response = new HTTPResponse("Login successful.", {
    user: { ...user },
    token,
  });
  return {
    statusCode: StatusCodes.OK,
    headers,
    body: JSON.stringify(response),
  };
});

模板.yaml

  LoginFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: login/
      Handler: app.loginHandler
      Runtime: nodejs20.x
      MemorySize: 3072
      Architectures:
        - x86_64
      Environment:
        Variables:
          MONGODB_URL: "mongodb://localhost:27017/10D"
          DB_NAME: "10D"
          JWT_SECRET: "awsSamLambdafunction2024node20jsX"
      Events:
        searchNodes:
          Type: Api
          Properties:
            Path: /api/user/login
            Method: post
    Metadata:
      SamResourceId: LoginFunction

我已经将登录功能的MemorySize增加到1024,仍然没有性能提升。

amazon-web-services aws-lambda lambda
1个回答
0
投票

您是否尝试过对 lambda 的不同部分进行计时?我怀疑数据库连接和请求可能会花费大量时间。

© www.soinside.com 2019 - 2024. All rights reserved.