使用 Azure 存储节点 SDK 创建队列消息时,队列触发的 Azure 函数抛出异常

Queue triggered Azure function throws exception when Queue message is created with the Azure Storage Node SDK

我使用 Azure Storage Node SDK 将消息添加到 Azure 存储队列。按照官方示例,我的代码如下所示:

const AzureStorage = require('azure-storage');
const queueService = AzureStorage.createQueueService();

queueService.createMessage('taskqueue', 'Hello world!', function (error) {
  if (!error) {
    // Message inserted
  }
});

这会向 taskqueue 队列添加一条消息,这又会触发使用 Node 构建的队列触发 Azure 函数。当 Azure Functions 收到消息时,它会抛出以下异常:

Exception while executing function: Functions.Function2. 
Microsoft.Azure.WebJobs.Host: Exception binding parameter 'queuedMessage'. 
mscorlib: The input is not a valid Base-64 string as it contains a non-base 
64 character, more than two padding characters, or an illegal character 
among the padding characters.

经过大量谷歌搜索,当我在官方文档中找不到任何内容时,我找到了 this excellent post

显然,通过 Azure 存储节点 SDK 对消息进行编码的方式(默认情况下)与通过队列触发的节点函数对消息进行解码的方式之间存在不一致。根据上面提到的 post,Azure 存储 SDK 默认使用 TextXmlQueueMessageEncoder,而 Azure 函数期望消息使用 TextBase64QueueMessageEncoder.

编码

新建@azure/storage-queue

新队列库中也存在不一致问题。在这个库中,我无法找到 built-in 切换编码器的方法,但是手动 base64 编码字符串可以解决问题:

const { QueueServiceClient } = require("@azure/storage-queue")

const base64Encode = (str) => Buffer.from(str).toString('base64')

const queueServiceClient = new QueueServiceClient(...)
queueServiceClient.getQueueClient('myqueue').sendMessage(base64Encode('Hello World!'))

azure-storage

在旧库中,手动覆盖默认编码器解决了问题。

const AzureStorage = require('azure-storage');
const QueueMessageEncoder = AzureStorage.QueueMessageEncoder;

const queueService = AzureStorage.createQueueService();
queueService.messageEncoder = new QueueMessageEncoder.TextBase64QueueMessageEncoder();
queueService.createMessage('taskqueue', 'Hello world!', function(error) {
  if (!error) {
    // Message inserted
  }
});