2

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

这将作为 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();
            }
        }
    }
    
4

1 回答 1

2

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

您可以轻松地EventProcessor在 WebJob 中托管。

于 2016-08-22T19:04:44.417 回答