【问题标题】:Adding messages to IAsyncCollector Topic output with a session ID使用会话 ID 将消息添加到 IAsyncCollector 主题输出
【发布时间】:2018-10-01 23:47:27
【问题描述】:

目前是否可以从 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.");
}

【问题讨论】:

    标签: c# azure azure-functions azureservicebus azure-servicebus-topics


    【解决方案1】:

    您需要绑定到 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。

    【讨论】:

    • 明白了。知道我如何将其作为另一个函数的输入吗?我似乎无法反序列化并将 AccountEventDTO 拉出主题(使用 v1)。
    • 如果您碰巧有时间看一下,这是我目前正在尝试解决的问题的链接,stackoverflow.com/questions/52612217/…
    猜你喜欢
    • 2022-11-25
    • 1970-01-01
    • 2020-11-05
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    相关资源
    最近更新 更多