如何在融合的Kafka C#中读取GenericRecord特定数据

时间:2019-04-23 13:31:02

标签: c# apache-kafka avro confluent-schema-registry confluent-kafka

这是我的简单代码段,试图读取Avro通用记录表单使用者:

using (var schemaRegistry = new CachedSchemaRegistryClient(new SchemaRegistryConfig { SchemaRegistryUrl = schemaRegistryUrl }))
  using (var consumer = new 
        ConsumerBuilder<string, GenericRecord>(new ConsumerConfig { BootstrapServers = bootstrapServers, GroupId = groupName })
                        .SetKeyDeserializer(new AsyncAvroDeserializer<string>(schemaRegistry).AsSyncOverAsync())
                        .SetValueDeserializer(new AsyncAvroDeserializer<GenericRecord>(schemaRegistry).AsSyncOverAsync())
                        .SetErrorHandler((_, e) => Console.WriteLine($"Error: {e.Reason}"))
                        .Build())
                {
      consumer.Subscribe(topicName);

      try
       {
           while (true)
             {
                try
                 {
                    var consumeResult = consumer.Consume();
                    Console.WriteLine($"Key: {consumeResult.Message.Key}\nValue: {consumeResult.Value}");
                    Console.WriteLine(consumeResult.Value.Schema);
                            Console.WriteLine(consumeResult.Value.Schema["favorite_number"]);

                  }
                 catch (ConsumeException e)
                   {
                       Console.WriteLine($"Consume error: {e.Error.Reason}");
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        // commit final offsets and leave the group.
                        consumer.Close();
                    }
                }

如您所见,我可以记录架构,但不知道如何获取其数据值。

 Console.WriteLine(consumeResult.Value.Schema);

 Console.WriteLine(consumeResult.Value.Schema["favorite_number"]);

与此对象consumeResult.Value中的模式和数据类似:

{架构:{“类型”:“记录”,“名称”:“用户”,“名称空间”:“ Confluent.Kafka.Examples.AvroSpecific”,“字段”:[{“名称”:“名称” ,“ type”:“ string”},{“ name”:“ favorite_number”,“ type”:[“ int”,“ null”]},{“ name”:“ favorite_color”,“ type”:[“ string “,” null“]}]},内容:{名称:sfs,收藏夹编号:41,收藏夹颜色:蓝色,}}

我想读取内容数据。

1 个答案:

答案 0 :(得分:0)

  

content无法访问

我认为Value.contents不是您想要的。正如您提到的,特别是因为该属性是private

getter的定义类似于字典-Source code

尝试consumeResult.Value["favorite_number"]


当您执行consumeResult.Value.Schema["favorite_number"]时,您会在模式中获得Field对象,而不是外部记录中字段的值。 -Source code