Mycat1.6 分片策略

Mycat支持多种分片策略,通过 rule.xmlschema.xml 配合使用。

1. 取模分片 (PartitionByMod)

根据分片键的值与节点数量取模,将数据均匀分布到各节点。

<table name="orders" dataNode="dn1,dn2,dn3" rule="mod-long" />

# rule.xml
<function name="mod-long" class="io.mycat.route.function.PartitionByMod">
    <property name="count">3</property>
</function>
适用场景数据量大、需要均匀分布的场景

2. 范围分片 (AutoPartitionByLong)

根据分片键的值范围分配到不同节点。

# autopartition-long.txt
# range start-end
0-5000000=0
5000001-10000000=1
10000001-15000000=2
适用场景有明确范围界限的数据,如按地区、按时间

3. 枚举分片 (PartitionByFileMap)

通过配置文件枚举值到节点的映射关系。

# partition-hash-int.txt
10000=0
10010=1
10020=2

# rule.xml
<function name="sharding-by-intfile"
    class="io.mycat.route.function.PartitionByFileMap">
    <property name="mapFile">partition-hash-int.txt</property>
    <property name="type">0</property>
    <property name="defaultNode">0</property>
</function>

4. 一致性哈希分片 (PartitionByMurmurHash)

使用MurmurHash算法,数据分布均匀且支持动态扩容。

<function name="murmur"
    class="io.mycat.route.function.PartitionByMurmurHash">
    <property name="seed">0</property>
    <property name="count">3</property>
    <property name="virtualBucketTimes">160</property>
</function>

5. 按日期(天)分片 (PartitionByDate)

按日期列将数据分散到不同节点。

<function name="partbyday"
    class="io.mycat.route.function.PartitionByDate">
    <property name="dateFormat">yyyy-MM-dd</property>
    <property name="sBeginDate">2019-01-01</property>
    <property name="sEndDate">2019-01-31</property>
    <property name="sPartionDay">10</property>
</function>

6. 按小时分片 (PartitionByHour)

<function name="sharding-by-hour"
    class="io.mycat.route.function.LatestMonthPartion">
    <property name="splitOneDay">24</property>
</function>

7. 字符串哈希分片

对字符串分片键进行哈希后取模。

<function name="sharding-by-string"
    class="io.mycat.route.function.PartitionByString">
    <property name="hashSlice">0:2</property>
    <property name="count">3</property>
</function>

8. ER关系分片

Mycat独创的ER关系分片,子表记录与父表关联记录存储在同一个节点。

<table name="customer" dataNode="dn1,dn2" rule="sharding-by-intfile">
    <childTable name="orders" primaryKey="id"
        joinKey="customer_id" parentKey="id" />
    <childTable name="customer_addr" primaryKey="id"
        joinKey="customer_id" parentKey="id" />
</table>

9. 全局表

全局表在所有数据节点都有完整数据副本,适合字典表、配置表。

<table name="hotnews" primaryKey="id" type="global" dataNode="dn1,dn2,dn3" />

分片策略选择建议

场景推荐策略
数据均衡分布取模分片 / 一致性哈希
按时间查询为主日期分片
按地区/业务类型枚举分片
关联表ER关系分片
字典/配置表全局表
ID连续增长范围分片
最佳实践: 分片键选择应尽量避免跨分片查询。尽量选择查询条件中出现频率最高的字段作为分片键。全局表不要太大。