使用KafkaTemplate <string,string =“”>发送时会返回使用String作为密钥的例外情况

时间:2019-01-03 09:12:52

标签: spring apache-kafka spring-kafka spring-kafka-test

当使用Integer作为键时,这不是问题,kafka应该能够将Strings作为键来处理。

ProducerFactory<String, String> pf =
                new DefaultKafkaProducerFactory<String, String>(senderProps);
KafkaTemplate<String, String> template = new KafkaTemplate<>(pf);
ProducerRecord<String,String> pr = new ProducerRecord<>("my-topic", "key1","test");
        template.send(pr);`

它抛出以下异常:

  

Org.apache.kafka.common.errors.SerializationException:无法转换   类java.lang.String的类的键   org.apache.kafka.common.serialization.IntegerSerializer中指定   key.serializer

     

原因:java.lang.ClassCastException:java.lang.String无法转换为java.lang.Integer         在org.apache.kafka.common.serialization.IntegerSerializer.serialize(IntegerSerializer.java:21)         在org.apache.kafka.common.serialization.ExtendedSerializer $ Wrapper.serialize(ExtendedSerializer.java:65)中         在org.apache.kafka.common.serialization.ExtendedSerializer $ Wrapper.serialize(ExtendedSerializer.java:55)         在org.apache.kafka.clients.producer.KafkaProducer.doSend(KafkaProducer.java:799)         在org.apache.kafka.clients.producer.KafkaProducer.send(KafkaProducer.java:784)         在org.springframework.kafka.core.DefaultKafkaProducerFactory $ CloseSafeProducer.send(DefaultKafkaProducerFactory.java:285)         在org.springframework.kafka.core.KafkaTemplate.doSend(KafkaTemplate.java:357)         在org.springframework.kafka.core.KafkaTemplate.send(KafkaTemplate.java:206)

1 个答案:

答案 0 :(得分:2)

似乎,您的密钥序列化程序在ProducerConfig中设置为Integer。您需要将KEY_SERIALIZER_CLASS_CONFIG设置为String:

@Bean
    public Map<String, Object> producerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        return props;
    }