一、分片枚举
本条规则通过在配置文件中配置的枚举进行分片
rule.xml
<tableRule name="sharding-by-intfile">
<rule>
<!-- 标识将要分片的表字段 -->
<columns>user_id</columns>
<!-- 分片函数 -->
<algorithm>hash-int</algorithm>
</rule>
</tableRule>
<function name="hash-int" class="io.mycat.route.function.PartitionByFileMap">
<!-- 配置文件名 -->
<property name="mapFile">partition-hash-int.txt</property>
<!-- 0表示Integer,1表示String -->
<property name="type">0</property>
<!-- 默认节点 如果不配置默认节点,碰到不识别的枚举值会报错 -->
<property name="defaultNode">0</property>
</function>
partition-hash-int.txt
10000=0
10010=1
# 所有节点配置是从0开始,即0代表节点1
用法:
字段user_id为10000进入节点1,字段user_id为10010进入节点2
二、固定分片hash算法
本条规则类似于十进制的求模运算,区别在于是二进制的操作,是取 id 的二进制低 10 位,即 id 二进制&1111111111
rule.xml
<tableRule name="rule1">
<rule>
<columns>user_id</columns>
<algorithm>func1</algorithm>
</rule>
</tableRule>
<function name="func1" class="io.mycat.route.function.PartitionByLong">
<!-- partitionCount 分片个数列表 -->
<property name="partitionCount">2,1</property>
<!-- partitionLength 分片范围列表 -->
<property name="partitionLength">256,512</property>
<!-- count,length 两个数组长度必须一致 -->
<!-- 1024 = sum((count[i]*length[i])). count 和 length 两个向量的点积恒等于 1024 -->
</function>
用法:
本例的分区策略:希望将数据水平分成 3 份,前两份各占 25%,第三份占 50%。(故本例非均匀分区)
// |<———————1024———————————>|
// |<—-256—>|<—-256—>|<———-512————->|
// | partition0 | partition1 | partition2 |
// | 共 2 份,故 count[0]=2 | 共 1 份,故 count[1]=1 |
如果需要平均分配设置:平均分为 4 分片,partitionCount*partitionLength=1024
<function name="func1" class="io.mycat.route.function.PartitionByLong">
<property name="partitionCount">4</property>
<property name="partitionLength">256</property>
</function>
三、范围约定
此分片适用于,提前规划好分片字段某个范围属于哪个分片
rule.xml
<tableRule name="auto-sharding-long">
<rule>
<columns>user_id</columns>
<algorithm>rang-long</algorithm>
</rule>
</tableRule>
<function name="rang-long" class="io.mycat.route.function.AutoPartitionByLong">
<property name="mapFile">autopartition-long.txt</property>
<property name="defaultNode">0</property>
</function>
autopartition-long.txt
# K=1000,M=10000
0-500M=0
500M-1000M=1
1000M-1500M=2
用法:
字段user_id为0-5000000进入节点1,以此类推
四、取模
此规则为对分片字段求摸运算
此种配置非常明确即根据 id 进行十进制求模预算,相比固定分片 hash,此种在批量插入时可能存在批量插入单
事务插入多数据分片,增大事务一致性难度
<tableRule name="mod-long">
<rule>
<columns>user_id</columns>
<algorithm>mod-long</algorithm>
</rule>
</tableRule>
<function name="mod-long" class="io.mycat.route.function.PartitionByMod">
<!-- how many data nodes -->
<property name="count">3</property>
</function>