此规则是截取字符串中的int数值hash分片
<tableRule name="sharding-by-stringhash"> <rule> <columns>user_id</columns> <algorithm>sharding-by-stringhash</algorithm> </rule> </tableRule> <function name="sharding-by-stringhash" class="org.opencloudb.route.function.PartitionByString" <property name=length>512</property> <!-- zero-based --> <property name="count">2</property> <property name="hashSlice">0:2</property> </function>
配置说明:
上面columns 标识将要分片的表字段,algorithm 分片函数
函数中length代表字符串hash求模基数,count分区数,hashSlice hash预算位,即根据子字符串中int值 hash运算
hashSlice : 0 means str.length(), -1 means str.length()-1
/**
- “2” -> (0,2)
- “1:2” -> (1,2)
- “1:” -> (1,0)
- “-1:” -> (-1,0)
- “:-1” -> (0,-1)
- “:” -> (0,0)
*/
例子:
String idVal=null; rule.setPartitionLength("512"); rule.setPartitionCount("2"); rule.init(); rule.setHashSlice("0:2"); // idVal = "0"; // Assert.assertEquals(true, 0 == rule.calculate(idVal)); // idVal = "45a"; // Assert.assertEquals(true, 1 == rule.calculate(idVal)); //last 4 rule = new PartitionByString(); rule.setPartitionLength("512"); rule.setPartitionCount("2"); rule.init(); //last 4 characters rule.setHashSlice("-4:0"); idVal = "aaaabbb0000"; Assert.assertEquals(true, 0 == rule.calculate(idVal)); idVal = "aaaabbb2359"; Assert.assertEquals(true, 0 == rule.calculate(idVal));