Skip to content

Producing messages

Matias Fontanini edited this page Apr 27, 2017 · 2 revisions

Message builder

In order to build a message, you need to use the MessageBuilder class, which allows setting each field in the message to whatever value you want.

// Construct a message builder for the kafka topic some_topic
MessageBuilder builder("some_topic");

// The key and value we'll use
const string key = "some_key";
const string payload = "Hello world!";

// Set the partition, key and payload. These can be easily chained.
builder.partition(10).key(key).payload(payload);

// Ready to be used!

Note that if you don't set a partition explicitly, this will be set to the unassigned partition (-1) so whatever configured partitioner callback will be called to determine the one to use.

MessageBuilder uses Buffer objects for the key and the payload. This means whatever was used to build those buffers (in the example above, the key and payload variables), need to be kept in scope until the message is sent to the producer.

Producing messages

Once you've built a MessageBuilder, producing its message is trivial:

// Build a producer from some Configuration object
Producer producer(config);

const string key = "some_key";
const string payload = "Hello world!";

// Build and produce the message
producer.produce(MessageBuilder("some_topic").key(key).payload(payload));
Clone this wiki locally