无法从 AWS Lambda 函数向 SQS 发送消息

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

我有一个 Lambda 函数,其中包含一些数据,必须将其发送到 SQS 队列。但似乎发送不起作用。没有错误,并且似乎优雅地继续执行,而没有发送任何消息。这是我的 Lambda 代码:

  //JavaScript

  import { SendMessageCommand, SQSClient } from "@aws-sdk/client-sqs";
  
  const message = {
    label: "test",
  };

  const client = new SQSClient({});
  const SQS_QUEUE_URL = "https://sqs.us-east-1.amazonaws.com/...";

  const send = async (message, sqsQueueUrl = SQS_QUEUE_URL) => {
    const command = new SendMessageCommand({
      QueueUrl: sqsQueueUrl,
      DelaySeconds: 5,
      MessageAttributes: {
        Label: {
          DataType: "String",
          StringValue: message.label,
        },
      },
      MessageBody:
        "Sent test data to SQS queue",
    });
    console.log("Test");
    const response = await client.send(command);
    console.log(response);
    return response;
  };
  
send(message, SQS_QUEUE_URL);

查看 CloudWatch 上的日志,我可以看到正在打印“Test”消息,但看不到响应。在

send(...)
之后我还有其他事情,所有代码都有效,只是
send(...)
没有做任何事情。我的运行时间是
Node.js 20.x

我已经附加了一项策略,为我的 Lambda 函数提供完整的 SQS 访问权限。我在初始化客户端时也包含了该区域,似乎没有什么区别。

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

您的

send
方法正在返回一个承诺,因此您必须等待响应(
await send(message, SQS_QUEUE_URL)
)才能满足 SQS 客户端(
client.send
)发出的请求,否则 lambda 实例将提前完成。我不知道您如何设置 lambda 处理程序,但我会给您一个应该如何重组代码的示例。

import { SendMessageCommand, SQSClient } from "@aws-sdk/client-sqs";

const message = {
  label: "test",
};

const client = new SQSClient({});
const SQS_QUEUE_URL = "https://sqs.us-east-1.amazonaws.com/...";

const send = async (message, sqsQueueUrl = SQS_QUEUE_URL) => {
  const command = new SendMessageCommand({
    QueueUrl: sqsQueueUrl,
    DelaySeconds: 5,
    MessageAttributes: {
      Label: {
        DataType: "String",
        StringValue: message.label,
      },
    },
    MessageBody:
      "Sent test data to SQS queue",
  });
  console.log("Test");
  const response = await client.send(command);
  console.log(response);
  return response;
};

export const handler = async (event) => {
  // Your code here

  await send(message, SQS_QUEUE_URL);

  // Your code here
};
© www.soinside.com 2019 - 2024. All rights reserved.