SQS Lambda 发布到同一堆栈中的同一 SQS

SQS Lambda Publish to same SQS in Same Stack

我正在尝试让 lambda 将 SQS 消息发布到 lambda 正在使用的同一个 SQS Url。但是,我无法找到如何在运行时获取队列 url 并且不想使用 AWS 机密。如何在运行时获取 SQS Url?

你最好的选择可能是在你的 lamda 函数中使用环境变量“QUEUE_NAME”或“QUEUE_URL”或类似的东西。不要忘记确保您的 lambda 函数具有正确的策略以允许它在 SQS 队列上发布新消息!

如果您可以提供有关您正在使用的语言的更多详细信息,并且如果您使用的是像 CDK 这样的 IaC,那么我可以提供一个代码示例。

PS。我不知道这个的确切应用,但要小心无限执行循环!

编辑:添加了以下代码示例:

using Amazon.CDK;
using Amazon.CDK.AWS.Lambda;
using Amazon.CDK.AWS.SQS;
using Amazon.CDK.AWS.Events;
using Amazon.CDK.AWS.Events.Targets;
using Amazon.CDK.AWS.Lambda.EventSources;

...
            // Function which gets called from cloudwatch event...
            var scheduledFunction = new Function(this, "scheduled-function", new FunctionProps
            {
                // add props here
            });
            
            // SQS Queue which is consumed and added to...
            var sqsQueue = new Queue(this, "sqs-queue", new QueueProps
            {
                // add props here
            });
            
            // Function which handles SQS messages from the queue...
            var messageHandlerFunction = new Function(this, "code-function", new FunctionProps
            {
                // add props here
                Environment = new Dictionary<string, string>
                {
                    {"SQS_URL",sqsQueue.QueueUrl}
                }
            });
            
            // Allow scheduler function to send SQS messages...
            sqsQueue.GrantSendMessages(scheduledFunction);

            // Allow scheduler function to consume and send SQS messages...
            sqsQueue.GrantConsumeMessages(messageHandlerFunction);
            sqsQueue.GrantSendMessages(messageHandlerFunction);
            
            // Set event message handler function to consume messages...
            messageHandlerFunction.AddEventSource(new SqsEventSource(sqsQueue));
            
            // Scheduled event to run every 30 minutes...
            var scheduledEvent = new Rule(this, "every-half-hour-rule", new RuleProps
            {
                Description = "Every 30 minutes.",
                Enabled = true,
                RuleName = "every-thirty-minutes",
                Schedule = null,
                Targets = new IRuleTarget[]
                {
                    new LambdaFunction(scheduledFunction)
                }
            });
...