如何在kafka制作人中切换到自定义编码器?

时间:2018-05-15 00:15:26

标签: java apache-kafka

当我尝试在kafka主题中使用string作为键时,我收到以下错误。

18/05/14 17:08:26 ERROR async.DefaultEventHandler: Error serializing message for topic my_topic
java.lang.ClassCastException: java.lang.String cannot be cast to [B
    at kafka.serializer.DefaultEncoder.toBytes(Encoder.scala:34)
    at kafka.producer.async.DefaultEventHandler$$anonfun$serialize$1.apply(DefaultEventHandler.scala:130)
    at kafka.producer.async.DefaultEventHandler$$anonfun$serialize$1.apply(DefaultEventHandler.scala:127)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
    at kafka.producer.async.DefaultEventHandler.serialize(DefaultEventHandler.scala:127)
    at kafka.producer.async.DefaultEventHandler.handle(DefaultEventHandler.scala:53)
    at kafka.producer.async.ProducerSendThread.tryToHandle(ProducerSendThread.scala:105)
    at kafka.producer.async.ProducerSendThread$$anonfun$processEvents$3.apply(ProducerSendThread.scala:88)
    at kafka.producer.async.ProducerSendThread$$anonfun$processEvents$3.apply(ProducerSendThread.scala:68)
    at scala.collection.immutable.Stream.foreach(Stream.scala:547)
    at kafka.producer.async.ProducerSendThread.processEvents(ProducerSendThread.scala:67)
    at kafka.producer.async.ProducerSendThread.run(ProducerSendThread.scala:45)

似乎问题是默认编码器

public class DefaultEncoder implements Encoder<byte[]> 

不支持字符串到字节

public byte[] toBytes(byte[] value) {
    return value;
}

向制作人提供自定义编码器的正确方法是什么?

我是否也必须在消费者方面进行改变?

1 个答案:

答案 0 :(得分:0)

在Producer / Consumer上,您可以指定不同的序列化程序,而不是默认的ByteArraySerializer,Here您可以找到版本1.1.0的可用序列化程序,或者您可以指定自己的序列化程序。

通常,如果您要发送/接收字符串或Json,则可以使用默认的org.apache.kafka.common.serialization.StringSerializerorg.apache.kafka.common.serialization.StringDeserializer。对于生产者/消费者,属性是:

private void configureProducer() {
    Properties props = new Properties();
    props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
}

private void configureConsumer() {
    Properties props = new Properties();
    props.put("key.serializer", "org.apache.kafka.common.serialization.StringDeserializer");
    props.put("value.serializer", "org.apache.kafka.common.serialization.StringDeserializer");
}

Properties producerProps = configureProducer();
KafkaProducer<String, String> producer = new KafkaProducer<>(producerProps);
Properties consumerProps = configureConsumer();
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(consumerProps);

如果要发送自己的自定义bean,则将其转换为json并使用默认的StringSerializer / Deserializer或构建自己的序列化/反序列化类。您可以使用带有spring boot here

的json字符串查看示例