MyCat系列十七--数据分片之一致性hash分片

MyCat系列十七--数据分片之一致性hash分片

解决方案goocz2025-06-12 11:29:334A+A-

MyCat系列十七--数据分片之一致性hash分片

一致性Hash算法有效的解决了分布式数据的扩容问题。

具体示例实现的步骤为如下(注:蓝色字体为本示例的相关内容):

  1. 新建表

CREATE TABLE `t_hash_2` (

`id` varchar(36) DEFAULT NULL,

`name` varchar(20) DEFAULT NULL

) ENGINE=InnoDB;

  1. 配置rule.xml

2.1 配置tableRule 标签

编辑rule.xml文件,增加或者修改如下:

<tableRule name="sharding-by-murmur-test">

<rule>

<columns>id</columns>

<algorithm>murmur-test</algorithm>

</rule>

</tableRule>

2.2 配置function 标签

编辑rule.xml文件,增加或者修改如下:

<function name="murmur-test" class="io.mycat.route.function.PartitionByMurmurHash">

<property name="seed">0</property>

<property name="count">3</property>

<property name="virtualBucketTimes">160</property>

</function>

一致性hash分片算法的相关property 子标签含义如下:

2.2.1 seed

默认是0

例如:

<property name="seed">0</property>

2.2.2 count

要分片的数据库节点数量,必须指定,否则没法分片。

例如:

<property name="count">3</property>

2.2.3 virtualBucketTimes

一个实际的数据库节点被映射为这么多虚拟节点,默认是160倍,也就是虚拟节点数是物理节点数的160倍。

例如:

<property name="virtualBucketTimes">160</property>

2.2.3 weightMapFile

节点的权重,没有指定权重的节点默认是1。以properties文件的格式填写,以从0开始到count-1的整数值也就是节点索引为key,以节点权重值为值。所有权重值必须是正整数,否则以1代替。

例如:

<property name="weightMapFile">weightMapFile</property>

2.2.3 bucketMapPath

用于测试时观察各物理节点与虚拟节点的分布情况,如果指定了这个属性,会把虚拟节点的murmur hash值与物理节点的映射按行输出到这个文件,没有默认值,如果不指定,就不会输出任何东西。

例如:

<property name="bucketMapPath">D:\mycat\bucketMapPath.txt</property>

  1. 配置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_hash_2" dataNode="dn1,dn2,dn3" rule="sharding-by-murmur-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,分别指向不同的服务器及其数据库,这里也就是数据分片的配置。本示例为了简单,配置到同一台服务器的不同数据库上。

  1. 验证

重启MyCat服务。然后,我们进行如下SQL语句执行验证:

insert into t_hash_2(id,name)

values ('
37efbeff-2f44-11f0-9f94-005056c00001','白梨')

,('
491d6260-2f44-11f0-9f94-005056c00001','张明')

,('
56db17fd-2f44-11f0-9f94-005056c00001','黎军');

select * from t_hash_2;

在MySQL的服务器上进行查询,如下所示:

select * from db_user_1.t_hash_2;

select * from db_user_2.t_hash_2;

select * from db_user_3.t_hash_2;

点击这里复制本文地址 以上内容由goocz整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!

果子教程网 © All Rights Reserved.  蜀ICP备2024111239号-5