1:分区器Partitioner
通过类图查看默认的Partitioner接口只有一个实现类DefaultPartitioner,也可以自己实现接口自定义
1.1:DefaultPartitioner默认分区器
每个topic都有一个固定的随机数作为开头,用于hash计算。
- 当消息被指定key时,直接计算hash获取分区数。
- 没有指定key时通过分区自增轮询写入分区中
public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
/*获取该topic所有的分区和分区的个数*/
List<PartitionInfo> partitions = cluster.partitionsForTopic(topic);
int numPartitions = partitions.size();
/*大多数情况我们是不指定key的*/
if (keyBytes == null) {
int nextValue = nextValue(topic);/*返回该topic所属的随机数*/
List<PartitionInfo> availablePartitions = cluster.availablePartitionsForTopic(topic);
if (availablePartitions.size() > 0) {
int part = Utils.toPositive(nextValue) % availablePartitions.size();
/*返回分区编码*/
return availablePartitions.get(part).partition();
} else {
// no partitions are available, give a non-available partition
return Utils.toPositive(nextValue) % numPartitions;
}
} else {
// hash the keyBytes to choose a partition指定了key,哈希keyBytes以选择分区,保证相同的key都进入了一个分区,保证有序性
return Utils.toPositive(Utils.murmur2(keyBytes)) % numPartitions;
}
}
//nextValue方法可以理解为是在消息记录中没有指定key的情况下,需要生成一个数用来代替key的hash值
//方法就是最开始先生成一个随机数,之后在这个随机数的基础上每次请求时均进行+1的操作
private int nextValue(String topic) {
AtomicInteger counter = topicCounterMap.get(topic);
if (null == counter) {
/*对于每个topic都有一个随机数作为起始的数值,用于计算*/
counter = new AtomicInteger(ThreadLocalRandom.current().nextInt());
AtomicInteger currentCounter = topicCounterMap.putIfAbsent(topic, counter);
if (currentCounter != null) {
counter = currentCounter;
}
}
// 以原子方式将当前值加 1。
return counter.getAndIncrement();
}