使用会话 ID 将消息添加到 IAsyncCollector 主题输出

Adding messages to IAsyncCollector Topic output with a session ID

目前是否可以将消息推送到 Azure 函数的 IAsyncCollector 主题输出并设置会话 ID?我的主题实际上是关于 FIFO 排序的,因此我们必须设置会话。正因为如此,我们曾设想只需将一个 Guid 设置为唯一的会话 ID。我知道如何通过此输出将消息推送到我的主题,但当然会出错,因为我们没有明确设置会话 ID。是否可以在我们将其发送到 IAsyncCollector 时在代码中的某处进行设置?

这是我们所拥有的,

[FunctionName("AccountCreatedHook")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req,
    TraceWriter log, [ServiceBus("topic-name", Connection = "busname", EntityType = Microsoft.Azure.WebJobs.ServiceBus.EntityType.Topic)] IAsyncCollector<AccountEventDTO> accountCreatedTopic)
{
    log.Info("C# HTTP trigger function processed a request.");

    // Get request body
    var accountEvent = await req.Content.ReadAsAsync<AccountEventDTO>();
    var payload = req.Content.ReadAsStringAsync().Result;

    if (accountEvent != null && accountEvent.Name != null)
    {
        await accountCreatedTopic.AddAsync(accountEvent);
        return req.CreateResponse(HttpStatusCode.OK, "Account successfully added to topic.");
    }

    return req.CreateResponse(HttpStatusCode.BadRequest, "Account was not formed well.");
}

您需要绑定到 Message (Azure Functions v2) 或 BrokeredMessage (Azure Functions v1),而不是直接绑定到 AccountEventDTO。然后就可以在消息上设置SessionId属性

要设置邮件正文,请将您的 DTO 序列化为 JSON 并对其进行 UTF-8 编码:

var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(accountEvent));
var message = new Message(bytes) { SessionId = sessionId };

对于 v2 或

var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(accountEvent));
var memoryStream = new MemoryStream(bytes, writable: false);
var message = new BrokeredMessage(memoryStream) { SessionId = sessionId };

对于 v1.