MyCat多重规则哈希分片

本文介绍了MyCat的分片规则,包括哈希取模、路由约定、范围路由、哈希范围和部分字段分片等,并重点讲解了如何实现自定义分片规则,通过继承特定类并实现相关方法。同时,文中还探讨了不带范围和带范围的复合规则分片,以及配置文件的设置方法。
摘要由CSDN通过智能技术生成

MyCat分片规则

MyCat自带的分片规则有很多种,而且支持自定义分片规则,灰常好用啊
感觉巨佬整理的很细,容易理解

  • 哈希取模分片:常见的分片方式,根据分片字段(一般是主键)的哈希值,再对分片个数取模运算,决定记录到哪个分片上;分片个数最好是2的n次方
  • 路由约定分片:维护一个properties文件,针对不同的值设置不同的分片
  • 范围路由约定分片:针对不同范围的值约定一个分片
  • 哈希范围约定分片:分片字段值哈希取模后的范围约定分片
  • 部分字段分片:截取某个字段的一部分作为分片依据,配合全局id生成器使用
  • 多重规则分片:设置多种分片规则,比如一部分采用路由分片,一部分采用哈希范围分片

自定义分片规则

MyCat支持自定义分片规则,自定义类需要继承AbstractPartitionAlgorithm类,然后实现calculate()calculateRange()方法

源码

这是看到了巨佬整理的博客,所幸自己也读懂了代码,忍不住自己也整理一下收获

  • AbstractPartitionAlgorithm源码
public abstract class AbstractPartitionAlgorithm implements RuleAlgorithm {
   

    @Override
    public void init() {
    }

    /**
     * 返回所有被路由到的节点的编号
     * 返回长度为0的数组表示所有节点都被路由(默认)
     * 返回null表示没有节点被路由到
     */
    @Override
    public Integer[] calculateRange(String beginValue, String endValue) {
        return new Integer[0];
    }

    /**
     * 对于存储数据按顺序存放的字段做范围路由,可以使用这个函数
     * @param algorithm
     * @param beginValue
     * @param endValue
     * @return
     */
    public static Integer[] calculateSequenceRange(AbstractPartitionAlgorithm algorithm, String beginValue, String endValue) {
        Integer begin = 0, end = 0;
        begin = algorithm.calculate(beginValue);
        end = algorithm.calculate(endValue);

        if(begin == null || end == null){
            return new Integer[0];
        }

        if (end >= begin) {
            int len = end-begin+1;
            Integer [] re = new Integer[len];

            for(int i =0;i<len;i++){
                re[i]=begin+i;
            }
            return re;
        }else{
            return null;
        }
    }

}
  • PartitionByMod源码
    private int count;

    @Override
    public void init() {}

    public void setCount(int count) {
        this.count = count;
    }

    @Override
    public Integer calculate(String columnValue) {
        BigInteger bigNum = new BigInteger(columnValue).abs();
        // 简单的对分片个数取模
        // x mod (2^n) = x&(2^n-1)
        return (bigNum.mod(BigInteger.valueOf(count))).intValue();
    }
  • 不带范围约定的符合规则分片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值