目的:有 user 和 t_order 两张数据表,表 user 的数据全部存放在 db1_zhang 中,表 t_order 的数据按 id 对 2 取模分别存放在 db1_zhang 和 db2_zhang 中。
1. 本地启动 2 个 MySQL 实例,端口分别设置为 3306 和 3307
3306 实例
create database db1_zhang; use db1_zhang; create table user(id int, name varchar(32)); create table t_order(id int, name varchar(32));
3307 实例
create database db2_zhang; use db2_zhang; create table t_order(id int, name varchar(32));
2. 配置 mycat,启动
server.xml
<user name="mycat"> <property name="password">mycat</property> <property name="schemas">TESTDB</property> </user>
rule.xml
<tableRule name="rule1"> <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">2</property> </function>
schema.xml
<!-- name="TESTDB" 与 server.xml中的 TESTDB 设置一致 --> <schema name="TESTDB" checkSQLschema="false" sqlMaxLimit="100"> <table name="user" primaryKey="id" dataNode="node1" /> <table name="t_order" primaryKey="id" dataNode="node1,node2" rule="rule1" /> </schema> <dataNode name="node1" dataHost="host1" database="db1_zhang" /> <dataNode name="node2" dataHost="host2" database="db2_zhang" /> <!-- 物理机的 url --> <dataHost name="host1" maxCon="1000" minCon="10" balance="0" writeType="0" dbType="mysql" dbDriver="native"> <heartbeat>select user()</heartbeat> <writeHost host="server1" url="127.0.0.1:3306" user="root" password="123456"/> </dataHost> <dataHost name="host2" maxCon="1000" minCon="10" balance="0" writeType="0" dbType="mysql" dbDriver="native"> <heartbeat>select user()</heartbeat> <writeHost host="server1" url="127.0.0.1:3307" user="root" password="123456"/> </dataHost>
3. 连接到 mycat,测试
mysql -umycat -pmycat -h127.0.0.1 -P8066 -DTESTDB
insert into user values(1, 'zhang'),(2, 'wang'); insert into t_order(id, name) values(1, 'book'),(2, 'phone'),(3, 'clothes');