MYCAT10种常见分片规则之八 — PartitionByString(字符串拆分)
转载:https://www.jianshu.com/p/0c48b20280be
一、使用场景
当分片索引不是纯整型的字符串时,只接受整型的内置hash算法是无法使用的。为此,stringhash按照用户定义的起点和终点去截取分片索引字段中的部分字符,根据当中每个字符的二进制unicode值换算出一个长整型数值,然后就直接调用内置hash算法求解分片路由:先求模得到逻辑分片号,再根据逻辑分片号直接映射到物理分片。建议在阅读本分片算法前,先阅读hash算法章节。
二、使用说明
1.指定分区字段名称。
2.类全名:io.mycat.route.function.PartitionByString
rule.xml 配置如下:
<tableRule name="sharding-by-stringhash">
<rule>
<columns>user_id</columns>
<algorithm>sharding-by-stringhash</algorithm>
</rule>
</tableRule>
<function name="sharding-by-substring" class="io.mycat.route.function.PartitionByString">
<property name=partitionLength>512</property> <!-- zero-based -->
<property name="partitionCount">2</property>
<property name="hashSlice">3:4</property>
</function>
配置说明:
上面 columns 标识将要分片的表字段,algorithm 分片函数函数中 partitionLength 代表字符串 hash 求模基数,
partitionCount 分区数,
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)
*/
注意:方向性,如 (0,-1)与 (-1,0) 是不同的。