- Building Data Streaming Applications with Apache Kafka
- Manish Kumar Chanchal Singh
- 338字
- 2022-07-12 10:38:14
Custom partition
Remember that we talked about key serializer and value serializer as well as partitions used in Kafka producer. As of now, we have just used the default partitioner and inbuilt serializer. Let's see how we can create a custom partitioner.
Kafka generally selects a partition based on the hash value of the key specified in messages. If the key is not specified/null, it will distribute the message in a round-robin fashion. However, sometimes you may want to have your own partition logic so that records with the same partition key go to the same partition on the broker. We will see some best practices for partitions later in this chapter. Kafka provides you with an API to implement your own partition.
In most cases, a hash-based default partition may suffice, but for some scenarios where a percentage of data for one key is very large, we may be required to allocate a separate partition for that key. This means that if key K has 30 percent of total data, it will be allocated to partition N so that no other key will be assigned to partition N and we will not run out of space or slow down. There can be other use cases as well where you may want to write Custom Partition. Kafka provides the partitioner interface, which helps us create our own partition.
Here is an example in Java:
public class CustomePartition implements Partitioner {
public int partition(String topicName, Object key, byte[] keyBytes, Object value, byte[] valueByte, Cluster cluster) {
List<PartitionInfo> partitions = cluster.partitionsForTopic(topicName);
int numPartitions = partitions.size();
//Todo: Partition logic here
return 0;
}
public void close() {
}
public void configure(Map<String, ?> map) {
}
}
Scala:
class CustomPartition extends Partitioner {
override def close(): Unit = {}
override def partition(topicName: String, key: scala.Any, keyBytes: Array[Byte], value: scala.Any, valueBytes: Array[Byte], cluster: Cluster): Int = {
val partitions: util.List[PartitionInfo] = cluster.partitionsForTopic(topicName)
val numPartitions: Int = partitions.size
//TODO : your partition logic here
0
}
override def configure(map: util.Map[String, _]): Unit = {}
}
- 區(qū)塊鏈架構(gòu)與實現(xiàn):Cosmos詳解
- 從程序員到架構(gòu)師:大數(shù)據(jù)量、緩存、高并發(fā)、微服務、多團隊協(xié)同等核心場景實戰(zhàn)
- Django Design Patterns and Best Practices
- R語言編程指南
- Learning Selenium Testing Tools(Third Edition)
- Java應用開發(fā)技術(shù)實例教程
- 劍指Java:核心原理與應用實踐
- BeagleBone Black Cookbook
- RabbitMQ Essentials
- Test-Driven Machine Learning
- Python Web自動化測試設(shè)計與實現(xiàn)
- Learning Bootstrap 4(Second Edition)
- Mastering OAuth 2.0
- 安卓工程師教你玩轉(zhuǎn)Android
- 體驗之道:從需求到實踐的用戶體驗實戰(zhàn)