3

I am new to the kafka eco system and in my case I'm using a Java producer but have no need for sending a key along with the record value which is serialized Avro. Is there a way to build a Java Producer to will not send keys, or are keys a requirement when sending messages in Kafka?

Duncan Krebs
  • 3,366
  • 2
  • 33
  • 53

2 Answers2

4

Like @gasparms said, there are built-in ways to produce without sending in a key. Most people use Kafka this way, since they just want to be able to send a stream of messages, with no key. Using keys is only really required if you need log compaction

Here's a really good explanation - https://stackoverflow.com/a/29515696/236528

mjuarez
  • 16,372
  • 11
  • 56
  • 73
2

ProducerRecord has several constructors, one of them don't have value for the key, so you don't have to indicate it.

Example:

Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

Producer<String, String> producer = new KafkaProducer<>(props);
for(int i = 0; i < 100; i++)
    producer.send(new ProducerRecord<>("my-topic", "myValue"));

producer.close();
gasparms
  • 3,336
  • 22
  • 26
  • Thanks for the fast answer, trying to get this done this morning :) Looks like I can use your example that uses a Producer Record constructor without a key. – Duncan Krebs Aug 07 '18 at 16:47
  • If I know that I'm not going to use keys when sending messages, is it possible to omit the configuration of the key serializer when creating the producer? I.e. the property "key.serializer". Also, is there the API where I do not have to specify the type of the key (as I'm not going to use it)? – fml2 Nov 22 '19 at 17:49