[schema.xml]配置
<dataNode name="dn1" dataHost="localhost1" database="db1"/> <dataNode name="dn2" dataHost="localhost1" database="db2"/> <dataNode name="dn3" dataHost="localhost1" database="db3"/>
把localhost1中的 db1-3 數(shù)據(jù)庫映射到mycat dn1-3 節(jié)點(diǎn)
規(guī)則種類,在rule.xml文件中
<table name="t_config" primaryKey="id" dataNode="dn1,dn2" rule="規(guī)則名" />
mycat全局表
如果你的業(yè)務(wù)中有些數(shù)據(jù)類似于數(shù)據(jù)字典,比如配置文件的配置,常用業(yè)務(wù)的配置或者數(shù)據(jù)量不大很少變動的表,這些表往往不是特別大,而且大部分的業(yè)務(wù)場景都會用到,那么這種表適合于 Mycat全局表,無須對數(shù)據(jù)進(jìn)行切分,只要在所有的分片上保存一份數(shù)據(jù)即可,Mycat 在Join 操作中,業(yè)務(wù)表與全局表進(jìn)行Join聚合會優(yōu)先選擇相同分片內(nèi)的全局表join,避免跨庫 Join,在進(jìn)行數(shù)據(jù)插入操作時,mycat將把數(shù)據(jù)分發(fā)到全局表對應(yīng)的所有分片執(zhí)行,在進(jìn)行數(shù)據(jù)讀取時候?qū)S機(jī)獲取一個節(jié)點(diǎn)讀取數(shù)據(jù)。
配置[schema.xml]
<table name="t_config" primaryKey="id" type="global" dataNode="dn1,dn2" />
ER分片表
有一類業(yè)務(wù),例如訂單(order)跟訂單明細(xì)(order_detail),明細(xì)表會依賴于訂單,也就是說會存在表的主從關(guān)系,這類似業(yè)務(wù)的切分可以抽象出合適的切分規(guī)則,比如根據(jù)用戶 ID切分,其他相關(guān)的表都依賴于用戶ID,再或者根據(jù)訂單ID切分,總之部分業(yè)務(wù)總會可以抽象出父子關(guān)系的表。這類表適用于 ER分片表,子表的記錄與所關(guān)聯(lián)的父表記錄存放在同一個數(shù)據(jù)分片上,避免數(shù)據(jù) Join跨庫操作。
以order與 order_detail例子為例,schema.xml中定義如下的分片配置,order,order_detail 根據(jù) order_id進(jìn)行數(shù)據(jù)切分,保證相同 order_id的數(shù)據(jù)分到同一個分片上,在進(jìn)行數(shù)據(jù)插入操作時,Mycat會獲取 order所在的分片,然后將 order_detail也插入到 order所在的分片。
配置[schema.xml]
<table name="t_order" primaryKey="id" dataNode="dn$1-3" rule="mod-long"> <childTable name="t_order_detail" primaryKey="id" joinKey="order_id" parentKey="id" /></table>
mycat配置
[schema.xml]
<table name="t_order" primaryKey="id" autoIncrement="true" dataNode="dn$1-3" rule="mod-long"> <childTable name="t_order_detail" primaryKey="id" autoIncrement="true" joinKey="order_id" parentKey="id" /></table>
[sequence_db_conf.properties]
#TABLE=dataNodeT_ORDER_DETAIL=dn1T_ORDER=dn1
[sequence_conf.properties]
T_ORDER.CURID=0T_ORDER.MINID=1T_ORDER.MAXID=10000T_ORDER_DETAIL.CURID=0T_ORDER_DETAIL.MINID=1T_ORDER_DETAIL.MAXID=10000
CURID表示當(dāng)前ID值,MINID表示最小ID值,MAXID表示最大ID值
重啟mycat,執(zhí)行sql
#創(chuàng)建數(shù)據(jù)庫create table t_order(id bigint not null auto_increment primary key,company varchar(255))AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;create table t_order_detail(id bigint not null auto_increment primary key,good varchar(255),order_id bigint,CONSTRAINT FK_ORDID11 FOREIGN KEY (ORDER_ID) REFERENCES T_ORDER (ID))AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;#插入數(shù)據(jù)insert into t_order(company) values('alibaba');insert into t_order(company) values('tencent');insert into t_order(company) values('baidu');insert into t_order_detail(good,order_id) values('aliyun',1);insert into t_order_detail(good,order_id) values('qq',2); insert into t_order_detail(good,order_id) values('baiduyun',3);
結(jié)論
登陸MySQL查看db1-3的記錄,可以發(fā)現(xiàn),三條order記錄在不同db上,order_detail的記錄與所關(guān)聯(lián)的order表記錄存放在同一個數(shù)據(jù)分片上