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();
}
- 不带范围约定的符合规则分片