以下代碼連接到Azure事件中心,它遍歷所有分區,然後讀取要處理並插入數據庫的消息(待完成) ,代碼工作正常,但每次讀取所有消息。根據最後消息日期改進代碼以從Event Hub讀取消息
這將作爲Azure WebJob安裝,因此它將持續運行,實時,不會停止。
- 如何改進此代碼以僅讀取未處理的消息?
有沒有更好的方法來編碼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(); } } }
目前的@gina代碼有什麼問題?也爲接收者,客戶端和工廠對象,你也確保你處理它們,也許這是最適合代碼審查的替代品。 – MethodMan
問題是它總是從事件中心讀取所有消息,創建接收者方法有一個日期時間偏移參數,她問是否有辦法只讀取尚未處理的消息。 –