admin管理员组文章数量:1596345
分片算法 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; }
本文标签: 算法分片MyCatPartitionByModPartitionByHashMod
版权声明:本文标题:Mycat 分片算法 PartitionByMod | PartitionByHashMod 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1728256509a1151079.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论