以下代码连接到 Azure 事件中心,它遍历所有分区,然后读取要处理的消息并将其插入数据库(待完成),代码工作正常,但每次它读取所有消息。
这将作为 Azure WebJob 安装,因此它将持续、实时、不间断地运行。
- 如何改进此代码以仅读取未处理的消息?
有没有更好的方法来编写 while/for 部分,你会用不同的方法吗?
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(); } } }