在 Go 中将消息从 Lambda 发送到 SQS

Send message from Lambda to SQS in Go

我正在寻找从用 Go 编写的 Lambda 函数向 SQS 队列发送 消息,我在 AWS 控制台中配置了该消息以便连接 SQS 队列作为目的地。

我看到的代码示例 (here) 建议我需要在发出消息之前加载 config、创建 client 并获取 queueURL通过调用 SendMsg。当 运行 本地代码时,这种方法工作正常,但在 Lambda 中似乎没有必要,因为我在控制台中连接 SQS 队列。当我已经连接到它作为目标时,是否需要告诉我的 Lambda 找到 queueURL?

顺便说一句,我尝试了这种方法,但是当 运行 Lambda 中的代码时收到以下错误。在本地调用 Lambda 外部的代码会毫无问题地找到 queueURL。

{
  "errorMessage": "operation error SQS: GetQueueUrl, https response error StatusCode: 400, RequestID: 2f725471-ec4e-5380-99ed-0f708c1fcfa4, AWS.SimpleQueueService.NonExistentQueue: ",
  "errorType": "OperationError"
}

这让我看到了另一面,我有一个 Lambda,它从队列中 消耗 ,因此将 SQS 队列配置为触发器。我只需要遍历 sqsEvent.Records 而不必指定 configclientqueueURL 因为我认为这是在幕后的控制台中处理的,即

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

func handler(ctx context.Context, sqsEvent events.SQSEvent) error {

    for _, message := range sqsEvent.Records {
        fmt.Printf("The message %s for event source %s = %s \n", message.MessageId, message.EventSource, message.Body)
    }

    return nil
}

func main() {
    lambda.Start(handler)
}

有没有一种方法可以从 Lambda 内部向队列发送消息而无需先找到 queueURL

I have configured so that the SQS queue is connected as a Destination.

发送消息不需要您定义 destination 本身 - 目的地用于传递异步 Lambda 函数调用结果。基本上 - 如果您不明确需要它们(并且您知道什么时候需要),它们将不是您所需要的。

授予您的 Lambda 权限以将消息发送到队列,并使用 SendMessage 使用 AWS SDK 发送消息。不需要目的地。

AWS.SimpleQueueService.NonExistentQueue

错误消息表明它没有找到队列,如果您在正确的区域中查找,可能 double-check。

I simply need to iterate over the sqsEvent.Records without having to specify config, client or queueURL as I presume this is handled in the console behind the scenes, i.e.

是的,这是抽象的 - 最终,您的 Lambda 函数由事件调用,并将 Amazon SQS 设置为触发器允许它向您的函数传递事件。

Is there a way of sending a message to a queue from within the Lambda without having to find the queueURL first?

让我们将其改写为 - 有没有一种方法可以向某人发送信件而无需找到他们的地址?当然不是,因为我们需要知道这封信要去哪里。

同样的概念也适用于 SQS 队列。