根据上次消息日期,改进从事件中心读取消息的代码



下面的代码连接到Azure Event Hub,它遍历所有分区,然后读取要处理的消息并插入到数据库中(待完成),代码工作正常,但是每次它读取所有消息。

这将作为Azure WebJob安装,因此它将连续运行,实时,不停止。

  1. 如何改进此代码以仅读取未处理的消息?
  2. 有没有更好的方法来编码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();
            }
        }
    }
    

使用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

最新更新