使用此代码添加到队列的消息未设置 TTL,即使在尝试了多次不同的迭代之后,我也无法理解为什么会出现这种情况。 Stack Overflow 希望我添加更多细节,但这是一个非常简洁的问题。
// Function to send a message to the queue with a TTL
const sendToQueue = async (messageContent, ttlInSeconds) => {
const credential = new DefaultAzureCredential();
const queueServiceClient = new QueueServiceClient(
`https://${storageAccountName}.queue.core.windows.net`,
credential
);
const queueClient = queueServiceClient.getQueueClient(queueName);
const message = JSON.stringify({ message: messageContent });
// Set the time-to-live (TTL) for the message (in seconds)
const options = {
timeToLive: ttlInSeconds // TTL is in seconds
};
await queueClient.sendMessage(message, options);
};
app.http('alert', {
methods: ['GET', 'POST'],
authLevel: 'anonymous',
handler: async (request, context) => {
console.log("JavaScript HTTP trigger function processed a request.");
const messageContent = request.query.get("message"); // Get the 'message' parameter from URL
if (messageContent) {
try {
// Your message sending logic here
const ttlInSeconds = 3600; // Set TTL to 1 hour (adjust as needed)
const result = await sendToQueue(messageContent, ttlInSeconds); // Pass TTL in seconds
return {
status: 200,
body: "Message added to the queue successfully.",
};
} catch (error) {
console.log("Error adding message to the queue:", error);
return {
status: 500,
body: "Internal server error.",
};
}
} else {
return {
status: 400,
body: "Please pass a 'message' parameter in the URL.",
};
}
}
});
我相信您无法设置消息 TTL 是因为您使用了不正确的属性名称。根据此处提供的文档,正确的属性名称是
messageTimeToLive
:https://learn.microsoft.com/en-us/javascript/api/%40azure/storage-queue/queuesendmessageoptions?view=azure-node-latest #@azure-storage-queue-queuesendmessageoptions-messagetimetolive.
请尝试使用以下代码:
const sendToQueue = async (messageContent, ttlInSeconds) => {
const credential = new DefaultAzureCredential();
const queueServiceClient = new QueueServiceClient(
`https://${storageAccountName}.queue.core.windows.net`,
credential
);
const queueClient = queueServiceClient.getQueueClient(queueName);
const message = JSON.stringify({ message: messageContent });
// Set the time-to-live (TTL) for the message (in seconds)
const options = {
messageTimeToLive: ttlInSeconds // TTL is in seconds
};
await queueClient.sendMessage(message, options);
};