kafka java producer api无法将密钥序列化为long或int

6psbrbz9  于 2021-06-05  发布在  Kafka
关注(0)|答案(1)|浏览(359)

以下是用kafka生成数据的java代码:

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.LongSerializer;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class ExampleClass {
  private final static String TOPIC = "my-example-topic";
  private final static String BOOTSTRAP_SERVERS = "confbroker:9092";

  private static Producer<Long, String> createProducer() {
    Properties props = new Properties();
    props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS);
    props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName());
    props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
    return new KafkaProducer<>(props);
  }
  private static void runProducer() throws Exception {
    final Producer<Long, String> producer = createProducer();
    long sensorId = 1001L;
    try {
      for (long index = sensorId; index < sensorId + 5; index++) {
        final ProducerRecord<Long, String> record = new ProducerRecord<>(TOPIC, index, "This is sensor no: " + index);
        RecordMetadata metadata = producer.send(record).get();
        System.out.printf("sent record(key=%s value=%s) " + "meta(partition=%d, offset=%d)\n", record.key(),
            record.value(), metadata.partition(), metadata.offset());
      }
    } finally {
      producer.flush();
      producer.close();
    }
  }
  public static void main(String... args) throws Exception {
      runProducer();
  }
}

在confluent 5.4.0中运行console consumer时,得到的结果如下:

关键是胡言乱语。
如何生成int或long类型的键。
附言:
=>汇合5.5的结果也相同。
=>与integerserializer的结果相同。

ngynwnxp

ngynwnxp1#

控制台使用者使用StringDeserializers作为键和值的默认值。如果要将密钥反序列化为 Long 您必须在控制台使用者命令中明确指出:

--property key.deserializer org.apache.kafka.common.serialization.LongDeserializer

相关问题