MyCat系列十五--数据分片之字符串hash求模范围
MyCat系列十五--数据分片之字符串hash求模范围
首先截取长度为 prefixLength 的子串,在对子串中每一个字符的 ASCII 码求和,然后对求和值进行 取模运算( sum%patternValue),计算出子串的分片数。
具体示例实现的步骤为如下(注:蓝色字体为本示例的相关内容):
- 新建表
CREATE TABLE `t_string_hash` (
`id` int DEFAULT NULL,
`name` varchar(20) DEFAULT NULL
) ENGINE=InnoDB;
- 配置rule.xml
2.1 配置tableRule 标签
编辑rule.xml文件,增加或者修改如下:
<tableRule name="sharding-by-prefixpattern-test">
<rule>
<columns>name</columns>
<algorithm>sharding-by-prefixpattern-test</algorithm>
</rule>
</tableRule>
2.2 配置function 标签
编辑rule.xml文件,增加或者修改如下:
<function name="sharding-by-prefixpattern-test" class="io.mycat.route.function.PartitionByPrefixPattern">
<property name="mapFile">partition-prefixpattern-test.txt</property>
<property name="prefixLength">5</property>
<property name="patternValue">96</property>
</function>
字符串hash求模范围算法的相关property 子标签含义如下:
2.2.1 mapFile
分片配置文件名,需要在此定义的文件中进行范围设置。
例如:
<property name="mapFile">partition-prefixpattern-test.txt</property>
2.2.2 prefixLength
求模基数。
例如:
<property name="prefixLength">5</property>
2.2.3 patternValue
求模基数。
例如:
<property name="patternValue">96</property>
- 创建partition-prefixpattern-test.txt文件
在conf目录下,新建
partition-prefixpattern-test.txt,并输入以下文本:
0-32=0
33-64=1
65-96=2
代表sum%96后的分布情况:
如果在0-32, 则在分片0上
如果在33-64, 则在分片1上
如果在65-96, 则在分片2上
- 配置schema.xml
<?xml version="1.0"?>
<!DOCTYPE mycat:schema SYSTEM "schema.dtd">
<mycat:schema xmlns:mycat="http://io.mycat/">
<schema name="testdb" checkSQLschema="true" sqlMaxLimit="100" randomDataNode="true">
<table name="t_string_hash" dataNode="dn1,dn2,dn3" rule="sharding-by-prefixpattern-test"></table>
</schema>
<dataNode name="dn1" dataHost="localhost" database="db_user_1" />
<dataNode name="dn2" dataHost="localhost" database="db_user_2" />
<dataNode name="dn3" dataHost="localhost" database="db_user_3" />
<dataHost name="localhost" maxCon="1000" minCon="10" balance="0"
writeType="0" dbType="mysql" dbDriver="native" switchType="1" slaveThreshold="100">
<heartbeat>select user()</heartbeat>
<writeHost host="localhost" url="localhost:3306" user="root"
password="123456">
</writeHost>
</dataHost>
</mycat:schema>
dataNode:数据节点,配置了dn1,dn2,dn3,分别指向不同的服务器及其数据库,这里也就是数据分片的配置。本示例为了简单,配置到同一台服务器的不同数据库上。
- 验证
重启MyCat服务。然后,我们进行如下SQL语句执行验证:
insert into t_string_hash(id,name)
values (1,'gf89f9a'),(2,'abcaa01'), (3,'xcpG902');
select * from t_string_hash;
在MySQL的服务器上进行查询,如下所示:
select * from db_user_1.t_string_hash;
select * from db_user_2.t_string_hash;
select * from db_user_3.t_string_hash;
从以上查询结果,可以看到数据的分片存储情况是正确的,见下面表格:
范围 | dataNode | 测试数据 | ASCII 码求和 | 取模96 |
0-32 | dn1 | abcaa01 | 488 | 8 |
33-64 | dn2 | gf89f9a | 420 | 36 |
65-96 | dn3 | xcpG902 | 459 | 75 |