Node.js 18 Lambda(AWS SDK V3)循环发送SQS消息问题求助
AWS Lambda(Node.js 18 + AWS SDK v3)循环发送SQS消息的正确实现
先解决你遇到的核心问题
await sqsClient.send(command)没执行:大概率是用了forEach循环——forEach不支持异步await,会直接跳过等待,导致Lambda函数提前结束,看起来send没执行。换成for...of或者用Promise.all批量处理就行。- 误以为send不是函数:AWS SDK v3的
send方法本身就返回Promise,不用像v2那样加.promise(),加了反而会报错。
官方基础单条消息示例(翻译自AWS官方文档)
先给你翻译官方的无循环基础示例,搞懂单条发送的正确姿势:
import { SendMessageCommand, SQSClient } from "@aws-sdk/client-sqs"; // 初始化SQS客户端,替换成你的AWS区域 const sqsClient = new SQSClient({ region: "us-east-1" }); // 封装单条消息发送逻辑 const sendSingleMessage = async (queueUrl, messageBody) => { const command = new SendMessageCommand({ QueueUrl: queueUrl, // 替换成你的SQS队列URL MessageBody: messageBody, DelaySeconds: 0, // 可选:消息延迟发送时间,单位秒 }); try { const response = await sqsClient.send(command); console.log(`消息发送成功,ID:${response.MessageId}`); return response; } catch (error) { console.error("消息发送失败", error); throw error; } }; // Lambda处理入口 export const handler = async (event) => { const queueUrl = "https://sqs.us-east-1.amazonaws.com/123456789012/your-queue"; await sendSingleMessage(queueUrl, "测试单条消息"); return { statusCode: 200, body: "单条消息发送完成" }; };
循环发送的两种正确实现
1. 串行逐条发送(保证顺序)
如果需要按顺序发送消息,用for...of循环(别用forEach):
import { SendMessageCommand, SQSClient } from "@aws-sdk/client-sqs"; const sqsClient = new SQSClient({ region: "us-east-1" }); const sendSingleMessage = async (queueUrl, messageBody) => { const command = new SendMessageCommand({ QueueUrl: queueUrl, MessageBody: messageBody, }); return sqsClient.send(command); }; export const handler = async (event) => { const queueUrl = "你的SQS队列URL"; // 待发送的消息列表 const messages = ["用户订单消息1", "用户订单消息2", "用户订单消息3"]; // 用for...of实现串行发送 for (const msg of messages) { try { const response = await sendSingleMessage(queueUrl, msg); console.log(`消息【${msg}】发送成功,ID:${response.MessageId}`); } catch (err) { console.error(`消息【${msg}】发送失败`, err); // 可选:如果想遇到错误就中断循环,就加throw err; } } return { statusCode: 200, body: "串行消息发送完成" }; };
2. 并行批量发送(效率更高)
如果不需要顺序,想提高发送速度,用Promise.all批量处理,注意这里send直接返回Promise,不用加.promise():
import { SendMessageCommand, SQSClient } from "@aws-sdk/client-sqs"; const sqsClient = new SQSClient({ region: "us-east-1" }); const sendSingleMessage = async (queueUrl, messageBody) => { const command = new SendMessageCommand({ QueueUrl: queueUrl, MessageBody: messageBody, }); // 直接返回send的Promise,不用加.promise()! return sqsClient.send(command); }; export const handler = async (event) => { const queueUrl = "你的SQS队列URL"; const messages = ["批量消息1", "批量消息2", "批量消息3"]; // 生成所有发送任务的Promise数组 const sendTasks = messages.map(async (msg) => { try { const response = await sendSingleMessage(queueUrl, msg); return { success: true, message: msg, messageId: response.MessageId }; } catch (err) { return { success: false, message: msg, error: err.message }; } }); // 等待所有任务完成 const results = await Promise.all(sendTasks); // 统计失败的消息 const failedMessages = results.filter(item => !item.success); if (failedMessages.length > 0) { console.error("部分消息发送失败", failedMessages); } return { statusCode: 200, body: JSON.stringify(results) }; };
额外注意事项
- 调整Lambda的执行超时时间:如果批量发送的消息数量多,默认的3秒超时可能不够,要改长一点。
- 控制并发数:如果消息数量极大,别直接用Promise.all一次性发几百条,可能触发SQS的请求限制,建议分批次发送(比如每10条一批)。
内容的提问来源于stack exchange,提问作者Stéphane GRILLON
相关产品推荐
相关产品推荐

