sending使用kafkatemplate< string,string>返回使用string作为键的异常

kyks70gy  于 2021-06-07  发布在  Kafka
关注(0)|答案(1)|浏览(455)

当使用整数作为键时,这不是问题,kafka应该能够将字符串作为键来处理。

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类的键转换为key.serializer中指定的org.apache.kafka.common.serialization.integerserializer类
原因:java.lang.classcastexception:java.lang.string不能转换为org.apache.kafka.common.serialization.integerserializer.serialize(integerserializer)中的java.lang.integer。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(默认kafkaproducerfactory)。java:285)在org.springframework.kafka.core.kafkatemplate.dosend(kafkatemplate。java:357)在org.springframework.kafka.core.kafkatemplate.send(kafkatemplate。java:206)

eeq64g8w

eeq64g8w1#

似乎,您的密钥序列化程序在producerconfig中设置为整数。你需要设置 KEY_SERIALIZER_CLASS_CONFIG 作为字符串:

@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;
    }

相关问题