2016-08-22 60 views
1

以下代碼連接到Azure事件中心,它遍歷所有分區,然後讀取要處理並插入數據庫的消息(待完成) ,代碼工作正常,但每次讀取所有消息。根據最後消息日期改進代碼以從Event Hub讀取消息

這將作爲Azure WebJob安裝,因此它將持續運行,實時,不會停止。

  1. 如何改進此代碼以僅讀取未處理的消息?
  2. 有沒有更好的方法來編碼while/for section,你會以不同的方式做到嗎?

    static void Main(string[] args) 
    { 
        ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(ConfigurationManager.AppSettings["ConnectionString"].ToString()); 
        builder.TransportType = TransportType.Amqp; 
        MessagingFactory factory = MessagingFactory.CreateFromConnectionString(ConfigurationManager.AppSettings["ConnectionString"].ToString()); 
        EventHubClient client = factory.CreateEventHubClient(ConfigurationManager.AppSettings["eventHubEntity"].ToString()); 
        EventHubConsumerGroup group = client.GetDefaultConsumerGroup(); 
    
        CancellationTokenSource cts = new CancellationTokenSource(); 
        System.Console.CancelKeyPress += (s, e) => 
        { 
         e.Cancel = true; 
         cts.Cancel(); 
         Console.WriteLine("Exiting..."); 
        }; 
        var d2cPartitions = client.GetRuntimeInformation().PartitionIds; 
    
        while (true) 
        { 
         foreach (string partition in d2cPartitions) 
         { 
          EventHubReceiver receiver = group.CreateReceiver(partition, DateTime.MinValue); 
          EventData data = receiver.Receive(); 
          Console.WriteLine("{0} {1} {2}", data.PartitionKey, data.EnqueuedTimeUtc.ToLocalTime(), Encoding.UTF8.GetString(data.GetBytes())); 
          var dateLastMessage = data.EnqueuedTimeUtc.ToLocalTime(); 
          receiver.Close(); 
          client.Close(); 
          factory.Close(); 
         } 
        } 
    } 
    
+0

目前的@gina代碼有什麼問題?也爲接收者,客戶端和工廠對象,你也確保你處理它們,也許這是最適合代碼審查的替代品。 – MethodMan

+0

問題是它總是從事件中心讀取所有消息,創建接收者方法有一個日期時間偏移參數,她問是否有辦法只讀取尚未處理的消息。 –

回答

1

使用EventHubReceiver不給你你所需要的控制。相反,您應該使用EventProcessorHost,它允許您可以用來恢復處理消息的檢查點。

請參閱http://blogs.biztalk360.com/understanding-consumer-side-of-azure-event-hubs-checkpoint-initialoffset-eventprocessorhost/https://blogs.msdn.microsoft.com/servicebus/2015/01/16/event-processor-host-best-practices-part-1/進行背景閱讀。

查看https://azure.microsoft.com/en-us/documentation/articles/event-hubs-csharp-ephcs-getstarted/#receive-messages-with-eventprocessorhost的教程。

您可以在WebJob中輕鬆容納EventProcessor