Apache Kafka and Avro: org.apache.avro.generic.GenericData$Record cannot be cast to com.harmeetsingh13.java.Customer

前端 未结 1 1135
情书的邮戳
情书的邮戳 2021-02-03 15:34

Whenever I am trying to read the message from kafka queue, I am getting following exception :

[error] (run-main-0) java.lang.ClassCastException: org.apache.avro         


        
相关标签:
1条回答
  • 2021-02-03 16:26

    This is the final code that would work, after discussing with @harmeen

    static { 
        kafkaProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "smallest"); 
        kafkaProps.put(ConsumerConfig.GROUP_ID_CONFIG, "CustomerCountryGroup1"); 
        kafkaProps.put("zookeeper.connect", "localhost:2181"); 
        kafkaProps.put("schema.registry.url", "http://localhost:8081"); 
        kafkaProps.put(KafkaAvroDeserializerConfig.SPECIFIC_AVRO_READER_CONFIG, true); 
    }
    
    public static void infiniteConsumer() throws IOException { 
    
    VerifiableProperties properties = new VerifiableProperties(kafkaProps); 
    StringDecoder keyDecoder = new StringDecoder(properties); 
    KafkaAvroDecoder valueDecoder = new KafkaAvroDecoder(properties); 
    
    Map<String, Integer> topicCountMap = new HashMap<>(); 
    topicCountMap.put("BrandNewTopics", 1); 
    
    ConsumerConnector consumer = createJavaConsumerConnector(new kafka.consumer.ConsumerConfig(kafkaProps)); 
    Map<String, List<KafkaStream<String, Object>>> consumerMap = consumer.createMessageStreams(topicCountMap, keyDecoder, valueDecoder); 
    
    KafkaStream stream = consumerMap.get("BrandNewTopics").get(0); 
    ConsumerIterator it = stream.iterator(); 
    
    while (it.hasNext()) { 
        MessageAndMetadata messageAndMetadata = it.next(); 
        String key = (String) messageAndMetadata.key(); 
        GenericRecord record = (GenericRecord) messageAndMetadata.message(); 
        Customer customer = (Customer) SpecificData.get().deepCopy(Customer.SCHEMA$, record); 
        System.out.println("Key: " + key); 
        System.out.println("Value: " + customer); 
    } 
    

    Things that got change:

    • Adding SPECIFIC_AVRO_READER_CONFIG property to true.
    • Using smallest to start from the beginning of the topic.
    • Using StringSerializer and StringDeserializer for keys.
    • Change both producer and consumer to reflect the previous change
    • Adjust the namespace for the Customer class that represents the Avro record.
    0 讨论(0)
提交回复
热议问题