19

Ho un ruolo di lavoro Azure che è responsabile per il controllo delle code di bus 4 di servizio. Attualmente, ho solo il metodo di loop per controllare manualmente le code.Utilizzando QueueClient.OnMessage in un ruolo di lavoratore azzurro

while(true) 
{ 
    //loop through my queues to check for messages 
} 

Con Azure SDK 2.0 è arrivata la possibilità di ascoltare i messaggi anziché il polling. Ma ogni esempio che ho visto utilizza un'app console con Console.ReadKey(). C'è un modo per avere il ruolo di lavoratore seduto e aspettare anche i messaggi?

ho provato:

public override void Run() 
{ 
    _queueProcessors.ForEach(x => x.OnMessage(Process); 
} 

dove _queueProcessors è un elenco di QueueClients e processo è un metodo privato che gestisce i messaggi. Tuttavia, il ruolo del lavoratore li registra e poi si riavvia.

Quindi qualcuno sa come fare un client coda di sedersi e aspettare su un messaggio?

risposta

38

seguito è un esempio di codice per questo:

using Microsoft.ServiceBus; 
using Microsoft.ServiceBus.Messaging; 
using Microsoft.WindowsAzure.ServiceRuntime; 
using System.Diagnostics; 
using System.Net; 
using System.Threading; 

namespace WorkerRoleWithSBQueue1 
{ 
    public class WorkerRole : RoleEntryPoint 
    { 
     // The name of your queue 
     const string QueueName = "demoapp"; 
     ManualResetEvent CompletedEvent = new ManualResetEvent(false); 

    // QueueClient is thread-safe. Recommended that you cache 
    // rather than recreating it on every request 
    QueueClient Client; 

    public override void Run() 
    { 
     OnMessageOptions options = new OnMessageOptions(); 
     options.AutoComplete = true; // Indicates if the message-pump should call complete on messages after the callback has completed processing. 
     options.MaxConcurrentCalls = 1; // Indicates the maximum number of concurrent calls to the callback the pump should initiate 
     options.ExceptionReceived += LogErrors; // Allows users to get notified of any errors encountered by the message pump 

     Trace.WriteLine("Starting processing of messages"); 
     // Start receiveing messages 
     Client.OnMessage((receivedMessage) => // Initiates the message pump and callback is invoked for each message that is recieved, calling close on the client will stop the pump. 
      { 
       try 
       { 
        // Process the message 
        Trace.WriteLine("Processing Service Bus message: " + receivedMessage.SequenceNumber.ToString()); 
       } 
       catch 
       { 
        // Handle any message processing specific exceptions here 
       } 
      }, options); 

     CompletedEvent.WaitOne(); 
    } 

    private void LogErrors(object sender, ExceptionReceivedEventArgs e) 
    { 
     if (e.Exception != null) 
     { 
      Trace.WriteLine("Error: " + e.Exception.Message); 
     } 
    } 

    public override bool OnStart() 
    { 
     // Set the maximum number of concurrent connections 
     ServicePointManager.DefaultConnectionLimit = 12; 

     // Create the queue if it does not exist already 
     Trace.WriteLine("Creating Queue"); 
     string connectionString = "*** provide your connection string here***"; 
     var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); 
     if (!namespaceManager.QueueExists(QueueName)) 
     { 
      namespaceManager.CreateQueue(QueueName); 
     } 

     // Initialize the connection to Service Bus Queue 
     Client = QueueClient.CreateFromConnectionString(connectionString, QueueName); 

     Trace.WriteLine("Sending messages..."); 
     // populate some messages 
     for (int ctr = 0; ctr < 10; ctr++) 
     { 
      Client.Send(new BrokeredMessage()); 
     } 

     return base.OnStart(); 
    } 

    public override void OnStop() 
    { 
     // Close the connection to Service Bus Queue 
     Client.Close(); 
     CompletedEvent.Set(); // complete the Run function 
     base.OnStop(); 
    } 
} 

}

+1

A quanto pare Google fu è migliore della mia. :) Grazie! – mccow002

+8

mccow002 Devi dare un po 'di credito a @abhishek. È un PM nel team di Windows Azure. Potrebbe benissimo aver scritto l'esempio prima che OnMessage fosse pubblico. :) –

+0

Molto bello, un vantaggio collaterale di questo approccio è che puoi uscire da OnMessage quando vuoi. Stavo cercando una forma di stato.Break (simile a Parallel.For), ma questo funziona bene. Grazie. – ProVega

Problemi correlati