コード例 #1
0
ファイル: Program.cs プロジェクト: paulrao99/IFramework
 public static Task CreateConsumerTask(string commandQueue, string consumerId, CancellationTokenSource cancellationTokenSource)
 {
     return(Task.Run(() =>
     {
         var consumer = new KafkaConsumer(zkConnectionString, commandQueue, $"{Environment.MachineName}.{commandQueue}", consumerId);
         try
         {
             foreach (var kafkaMessage in consumer.GetMessages(cancellationTokenSource.Token))
             {
                 var message = Encoding.UTF8.GetString(kafkaMessage.Payload);
                 var sendTime = DateTime.Parse(message);
                 Console.WriteLine($"consumer:{consumer.ConsumerId} {DateTime.Now.ToString("HH:mm:ss.fff")} consume message: {message} cost: {(DateTime.Now - sendTime).TotalMilliseconds}");
                 consumer.CommitOffset(kafkaMessage.PartitionId.Value, kafkaMessage.Offset);
             }
         }
         catch (OperationCanceledException)
         {
             return;
         }
         catch (ThreadAbortException)
         {
             return;
         }
         catch (Exception ex)
         {
             if (!cancellationTokenSource.IsCancellationRequested)
             {
                 Console.WriteLine(ex.GetBaseException().Message);
             }
         }
         finally
         {
             consumer.Stop();
         }
     }));
 }