以枚举法,取余法为例:
枚举法:sharding-by-intfile
在schema.xml中,有:
<table name="employee" primaryKey="ID" dataNode="dn1,dn2,dn3" rule="sharding-by-intfile" />
# 其中表明了,在employee中必须要有ID这个字段,采用的分片规则是sharding-by-intfile枚举
vim rule.xml #查看分片规则
<tableRule name="sharding-by-intfile">
<rule>
<columns>sharding_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> #函数调用的配置文件
</function>
vim partition-hash-int.txt #修改调用配置文件
10000=0 #当sharding_id字段的值是10000时,数据存储在数据节点dn1里
10010=1 #当sharding_id字段的值是10010时,数据存储在数据节点dn2里
10020=2 #当sharding_id字段的值是10020时,数据存储在数据节点dn3里
通过以上信息可以看出,employee表采用的是枚举的分片方式
employee表中必须包括ID和sharding_id两个字段
sharding_id必须从10000,10010,10020这三个值当中选择
重启mycat:/usr/local/mycat/bin/mycat restart
远程建表:(在client上连接分片服务器)
mysql -h192.168.4.151 -P8066 -uroot -p123456
mysql>use TESTDB;
# 操作会同步到数据库服务器上
create table employee(
ID int primary key, #分片要求的主键
sharding_id int, #根据这个字段进行分片
name char(10),
age int
);
插入数据进行验证
insert into employee(ID, sharding_id , name, age) values(1,10000,"jason",20) #dn1
insert into employee(ID, sharding_id , name, age) values(1,10010,"jack",22) #dn2
insert into employee(ID, sharding_id , name, age) values(1,10020,"john",21) #dn3
# 在三台数据库上查找的数据不同,
# 通过client连接mycat使用select * from employee 可以查找到所有数据
取余法:mod-long
在schema.xml中,有:
<table name="hotnews" dataNode="dn1,dn2,dn3" rule="mod-long" />
# 其中表明了,hotnews这个表采用mod-long的分片方式
vim rule.xml #查看分片规则
<tableRule name="mod-long">
<rule>
<columns>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> #指定求模数字,id%3
</function>
通过以上信息可以看出hotnews中必须要有id这个字段,因为需要根据这个字段进行分片
分片的规则是对3取余,id%3
重启mycat:/usr/local/mycat/bin/mycat restart
远程建表:(在client上连接分片服务器)
mysql -h192.168.4.151 -P8066 -uroot -p123456
mysql>use TESTDB;
# 操作会同步到数据库服务器上
create table hotnews(
id int primary key, #分片要求根据这个字段进行分片,id可以不是主键,最后定义成主键
name char(10),
age int
);
插入数据验证:
insert into hotnews(id,name,aget)values(1,"jack",22) #dn2
insert into hotnews(id,name,aget)values(2,"marry",29) #dn3
insert into hotnews(id,name,aget)values(3,"jagger",27) #dn1
# 在三台数据库服务器中可以查到不同的数据
# client连接mycat服务器使用select * from hotnews可以看到所有的数据
写总结的第四十二天!!!