簡體   English   中英

Azure服務總線“ ReceiveAsync”

[英]Azure Service Bus “ReceiveAsync”

有沒有辦法使用Microsoft.Azure.ServiceBus包在您當前的線程上等待從隊列接收消息?

就我的理解和以不打算使用該技術的方式使用該技術而言,這可能更多是一個問題,但是我想做的是結合以下Microsoft示例中的發送和接收示例,以便您可以將消息發送到各個隊列,並能夠偵聽和處理“答復”(僅是您正在隊列中偵聽的消息)並在完成接收消息后關閉連接。

一些偽代碼在這里:

   // send message(s) that will be consumed by other processes / applications, and by doing so later on we will expect some messages back
   await SendMessagesAsync(numberOfMessages);

    var receivedMessages = 0;
    while (receivedMessages < numberOfMessages)
    {
        // there is no "ReceiveAsync" method, this is what I would be looking for
        Message message = await queueClient.ReceiveAsync(TimeSpan.FromSeconds(30));
        receivedMessages++;

        // do something with the message here
   }

   await queueClient.CloseAsync();

這可能嗎?還是我“做錯了”?

在新庫中, MessageReceiver類提供了ReceiveAsync方法:

var messageReceiver = new MessageReceiver(SBConnString, QueueName, ReceiveMode.PeekLock);
Message message = await messageReceiver.ReceiveAsync();

請參閱“開始使用MessageSender和MessageReceiver從服務總線隊列發送和接收消息”中的完整示例。

Microsoft.Azure.ServiceBus庫中,沒有所謂的ReceiveAsync這樣的東西。 在這種情況下,您可以使用RegisterOnMessageHandlerAndReceiveMessages()處理或接收消息。 這樣,您可以接收帶有事件的消息。 有了這個RegisterOnMessageHandlerAndReceiveMessages()就像queueClient.RegisterMessageHandler(ReceiveOrProcessMessagesAsync, messageHandlerOptions); 並且您必須分別為receiveMessages創建此事件,在我們的例子中是ReceiveOrProcessMessagesAsync

static async Task ReceiveOrProcessMessagesAsync(Message message, CancellationToken token)
    {
        // Process the message
        Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");

        // Complete the message so that it is not received again.
        // This can be done only if the queueClient is created in ReceiveMode.PeekLock mode (which is default).
        await queueClient.CompleteAsync(message.SystemProperties.LockToken);

        // Note: Use the cancellationToken passed as necessary to determine if the queueClient has already been closed.
        // If queueClient has already been Closed, you may chose to not call CompleteAsync() or AbandonAsync() etc. calls 
       // to avoid unnecessary exceptions.
    }

並且您參考以下鏈接以了解有關Microsoft.Azure.ServiceBus https://docs.microsoft.com/zh-cn/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM