concept StreamPartitioner in category kafka

This is an excerpt from Manning's book Kafka Streams in Action: Real-time apps and microservices with the Kafka Streams API.
The KStream.to method is a mirror image of the KStream.source method. Instead of setting a source for the topology to read from, the KStream.to method defines a sink node that’s used to write the data from a KStream instance to a Kafka topic. The KStream.to method also provides overloaded versions in which you can leave out the Produced parameter and use the default Serdes defined in the configuration. One of the optional parameters you can set with the Produced class is StreamPartitioner, which we’ll discuss next.
Although, in this simple example, you replaced the null key with a concrete value, repartitioning need not always change the key. By using StreamPartitioner (http://mng.bz/9Z8A), you can apply just about any partition strategy you can think of, such as partitioning on the value or part of the value instead of the key. In the next section, we’ll demonstrate using StreamPartitioner in Kafka Streams.
If you’ve modified or changed keys and you don’t need a custom partition strategy, you can rely on the DefaultPartitioner of the internal Kafka Streams KafkaProducer to handle the partitioning. But if you’d like to apply your own partitioning approach, you can use StreamPartitioner. You’ll do just that in the next example.
The code for using the KStream.through method is shown in the following listing. In this example, KStream.through() takes two parameters: the topic name and a Produced instance that provides the key Serde, the value Serde, and a StreamPartitioner. Note that if you want to use the default key and value Serde instances and have no need for a custom partitioning strategy, there’s a version of KStream.through where you only provide the topic name.
Listing 4.4. Using the KStream.through method
RewardsStreamPartitioner streamPartitioner = new RewardsStreamPartitioner(); #1 KStream<String, Purchase> transByCustomerStream = purchaseKStream.through("customer_transactions", Produced.with(stringSerde, purchaseSerde, streamPartitioner)); #2Here, you’ve instantiated a RewardsStreamPartitioner. Let’s take a quick look at how it works as well as demonstrate how to create a StreamPartitioner.