K
- the type of keysV
- the type of valuespublic interface StreamPartitioner<K,V>
DefaultPartitioner
will be used to determine the partition.
Kafka topics are divided into one or more partitions. Since each partition must fit on the servers that host it, so using multiple partitions allows the topic to scale beyond a size that will fit on a single machine. Partitions also enable you to use multiple instances of your topology to process in parallel all of the records on the topology's source topics.
When a topology is instantiated, each of its sources are assigned a subset of that topic's partitions. That means that only those processors in that topology instance will consume the records from those partitions. In many cases, Kafka Streams will automatically manage these instances, and adjust when new topology instances are added or removed.
Some topologies, though, need more control over which records appear in each partition. For example, some topologies that have stateful processors may want all records within a range of keys to always be delivered to and handled by the same topology instance. An upstream topology producing records to that topic can use a custom stream partitioner to precisely and consistently determine to which partition each record should be written.
To do this, create a StreamPartitioner
implementation, and when you build your topology specify that custom partitioner
when adding a sink
for that topic.
All StreamPartitioner implementations should be stateless and a pure function so they can be shared across topic and sink nodes.
Modifier and Type | Method and Description |
---|---|
java.lang.Integer |
partition(java.lang.String topic,
K key,
V value,
int numPartitions)
Determine the partition number for a record with the given key and value and the current number of partitions.
|
java.lang.Integer partition(java.lang.String topic, K key, V value, int numPartitions)
topic
- the topic name this record is sent tokey
- the key of the recordvalue
- the value of the recordnumPartitions
- the total number of partitionsnumPartitions-1
, or null
if the default partitioning logic should be used