Mycat 分片算法 PartitionByMod | PartitionByHashMod

分片算法 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;
    }

     

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wyr2018

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值