Spring Split Kafka
What is the difference in behavior of the below code snippets for posting?
Approach 1
Message<String> message = MessageBuilder.withPayload("testmsg")
.setHeader(KafkaHeaders.MESSAGE_KEY, "key").setHeader(KafkaHeaders.TOPIC, "test").build();
ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(message);
Approach 2
ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send("test", "testmsg");
Theme configuration:
$ bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic test
Topic:test PartitionCount:3 ReplicationFactor:1 Configs:
Topic: test Partition: 0 Leader: 0 Replicas: 0 Isr: 0
Topic: test Partition: 1 Leader: 0 Replicas: 0 Isr: 0
Topic: test Partition: 2 Leader: 0 Replicas: 0 Isr: 0
Comment:
If there are 3 consumers, one per section; Approach 1 results in all messages being consumed by one consumer from one section. Approach 2; consumption is split equally among the three sections / consumers.
source to share
But you have the answer in code. The first, along with topic
, provides messageKey
.
messageKey
is actually used to define the target section if not explicitly specified:
/**
* computes partition for given record.
* if the record has partition returns the value otherwise
* calls configured partitioner class to compute the partition.
*/
private int partition(ProducerRecord<K, V> record, byte[] serializedKey, byte[] serializedValue, Cluster cluster) {
Integer partition = record.partition();
return partition != null ?
partition :
partitioner.partition(
record.topic(), record.key(), serializedKey, record.value(), serializedValue, cluster);
}
where DefaultPartitioner
does the following:
List<PartitionInfo> partitions = cluster.partitionsForTopic(topic);
int numPartitions = partitions.size();
if (keyBytes == null) {
int nextValue = nextValue(topic);
...
} else {
// hash the keyBytes to choose a partition
return Utils.toPositive(Utils.murmur2(keyBytes)) % numPartitions;
}
So, all messages with the same are key
sent to the same section. Otherwise, they are placed in the circle of the theme.
source to share