2017-08-25 132 views
2

Kafka使用math.abs(key.hashCode)%numPartitions来计算要发送的分区。Kafka的分区选择算法

如果hashCode为Integer.MIN_VALUE,该怎么办?

由于math.abs(Integer.MIN_VALUE)是一个负数,卡夫卡会发送到负分区。这是如何处理的,我应该关心这个吗?

+0

正如你所说,它首先使用math.abs(),那么为什么你担心这种情况呢? – GuangshengZuo

+0

这不是一个坏问题:尝试比在repl:'math.abs(Integer.MIN_VALUE)'打印:'res0:Int = -2147483648' –

+0

相关:https://stackoverflow.com/questions/5444611/math- abs-returns-wrong-value-for-integer-min-value#5444634 –

回答

1

其实,当我在kafka代码中搜索它时,它不使用math.abs()将负值转换为正值。

它使用:

public static int toPositive(int number) { 
    return number & 0x7fffffff; 
} 

,因此它可以解决这个问题,你担心即使号码是2147483648,它会被转换为0

一种廉价的方式向确定性转换号码到正值。当输入为 为正时,返回原始值。当输入数字为负时,返回的 正值是原始值位AND与0x7fffffff的比值,而不是其绝对值 的值。

+0

真的吗?哪个版本? – ntysdd

+0

这是java kafka客户端,它也在kafka代码库中。你可以在https://github.com/apache/kafka/blob/trunk/clients/src/main/java/org/apache/kafka/common/utils/Utils.java找到。这不是新功能.. – GuangshengZuo

+0

而defaultPartitioner是在https://github.com/apache/kafka/blob/trunk/clients/src/main/java/org/apache/kafka/clients/producer/internals/DefaultPartitioner .java – GuangshengZuo