rule可以自己编写比较函数,系统提供了Long 和 String的 其中Long用于例子的已经讲解的很详细。
代码中已经将count和length之积写死,我们要做的是提供count和length要符合这个要求。
可以在PartitionUtil.java中找到;
// 分区长度:数据段分布定义,其中取模的数一定要是2^n, 因为这里使用x % 2^n == x & (2^n - 1)等式,来优化性能。
private static final int PARTITION_LENGTH = 1024;
下面贴一个按照String作为规则的rule:
<?xml version="1.0" encoding="UTF-8"?>
<!--
- Copyright 1999-2012 Alibaba Group.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-->
<!DOCTYPE cobar:rule SYSTEM "rule.dtd">
<cobar:rule xmlns:cobar="http://cobar.alibaba.com/">
<!-- 路由规则定义,定义什么表,什么字段,采用什么路由算法 -->
<tableRule name="rule2">
<rule>
<columns>siteid</columns>
<algorithm><![CDATA[diffsite(${siteid}) ]]></algorithm>
</rule>
</tableRule>
<function name="diffsite" class="com.alibaba.cobar.route.function.PartitionByString">
<property name="partitionCount">512</property>
<property name="partitionLength">2</property>
<property name="hashSlice">-5:</property>
</function>
</cobar:rule>
如果使用的是
PartitionByString
那么则根据提供的String的hash值来做判断,如果hash是1那么就将该条记录分布在第一个库里。如果是2则分布在第二个库里。hash值可以计算某一段String里的,其hash方式如下,类似python。
/**
* "2" -> (0,2)<br/>
* "1:2" -> (1,2)<br/>
* "1:" -> (1,0)<br/>
* "-1:" -> (-1,0)<br/>
* ":-1" -> (0,-1)<br/>
* ":" -> (0,0)<br/>
*/
public static Pair<Integer, Integer> sequenceSlicing(String slice) {
int ind = slice.indexOf(':');
if (ind < 0) {
int i = Integer.parseInt(slice.trim());
if (i >= 0) {
return new Pair<Integer, Integer>(0, i);
} else {
return new Pair<Integer, Integer>(i, 0);
}
}
String left = slice.substring(0, ind).trim();
String right = slice.substring(1 + ind).trim();
int start, end;
if (left.length() <= 0) {
start = 0;
} else {
start = Integer.parseInt(left);
}
if (right.length() <= 0) {
end = 0;
} else {
end = Integer.parseInt(right);
}
return new Pair<Integer, Integer>(start, end);
}
说明 如下:
str = ’0123456789′
print str[0:3] #截取第一位到第三位的字符
print str[:] #截取字符串的全部字符
print str[6:] #截取第七个字符到结尾
print str[:-3] #截取从头开始到倒数第三个字符之前
print str[2] #截取第三个字符
print str[-1] #截取倒数第一个字符
print str[::-1] #创造一个与原字符串顺序相反的字符串
print str[-3:-1] #截取倒数第三位与倒数第一位之前的字符
print str[-3:] #截取倒数第三位到结尾
print str[:-5:-3] #逆序截取,具体啥意思没搞明白?