分片算法 PartitionByMod 和 PartitionByHashMod 类似,只是在支持的字端类型上有稍微区别,放在一起说明:
<function name="part-by-mod" class="io.mycat.route.function.PartitionByMod">
<property name="count">3</property>
</function>
<function name="part-by-hashMod" class="io.mycat.route.function.PartitionByHashMod">
<property name="count">3</property>
</function>
count 表示 dataNode 个数,该属性必须配置,否则在插入数据计算 dataNode 时会抛出异常:ArithmeticException: BigInteger: modulus not positive。
关于两个算法的 calculate 方法具体实现如下:
PartitionByMod:
@Override
public Integer calculate(String columnValue) {
try {
BigInteger bigNum = new BigInteger(columnValue).abs();
return (bigNum.mod(BigInteger.valueOf(count))).intValue();
} catch (NumberFormatException e){
throw new IllegalArgumentException(new
StringBuilder().append("columnValue:").append(columnValue).append(" Please
eliminate any quote and non number within it.").toString(),e);
}
}
PartitionByHashMod:
@Override
public Integer calculate(String columnValue) {
BigInteger bigNum = new BigInteger(hash(columnValue.hashCode()) + "").abs();
if (watch) {
return bigNum.intValue() & (count - 1);
}
return (bigNum.mod(BigInteger.valueOf(count))).intValue();
}
通过以上代码,可以看出,两个方法算法都是对 columnValue 处理后和 count 模运算得出存储数据的dataNode。不同的是:
- PartitionByMod由于是直接用 columnValue 创建 BigInteger,所以 配置的 column 的数据类型必须能够转换为数字,如果是普通字符型,会抛出 IllegalArgumentException 异常,异常信息:“columnValue:wcy Please eliminate any quote and non number within it.
- PartitionByHashMod由于会对columnValue 做 hash,所以并不强制要求 column 的数据类型是数字,也可以是字符型。其 hash 算法如下:
protected int hash(int key) { key = (~key) + (key << 21); // key = (key << 21) - key - 1; key = key ^ (key >> 24); key = (key + (key << 3)) + (key << 8); // key * 265 key = key ^ (key >> 14); key = (key + (key << 2)) + (key << 4); // key * 21 key = key ^ (key >> 28); key = key + (key << 31); return key; }
更多推荐
Mycat 分片算法 PartitionByMod | PartitionByHashMod
发布评论