1、添加数据库、存储数据源
我们在读写分离那边已经生成过,不需要在执行,如果没有执行过,执行下面注解,我们这边重新创建一个数据库db1
/*+ mycat:createDatasource{ "name":"rwSepw", "url":"jdbc:mysql://192.168.200.51:3306/db1?useSSL=false&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true", "user":"root", "password":"123"} */;
/*+ mycat:createDatasource{ "name":"rwSepr", "url":"jdbc:mysql://192.168.200.53:3306/db1?useSSL=false&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true", "user":"root", "password":"123"} */;
create database db1;
2、添加集群配置
把新添加的数据源配置成集群
#在 mycat 终端输入
/*!
mycat:createCluster{"name":"c0","masters":["rwSepw"],"replicas":["rwSepr"]}
*/;
#可以查看集群配置信息
cd /usr/local/mycat/conf/clusters
注解生成如下结果
3、创建分片表(分库分表)
在 Mycat2数据客户端直接运行建表语句进行数据分片
CREATE TABLE db1.orders(
id BIGINT NOT NULL AUTO_INCREMENT,
order_type INT,
customer_id INT,
amount DECIMAL(10,2),
PRIMARY KEY(id),
KEY `id` (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
dbpartition BY mod_hash(customer_id) tbpartition BY mod_hash(customer_id) tbpartitions 2 dbpartitions 1;
数据库分片规则,表分片规则,以及各分多少片 tbpartitions 表数量 dbpartitions 库数量
查看生成的配置信息:
vim /usr/local/mycat/conf/schemas/db1.schema.json
4、 查看数据库,插入数据
INSERT INTO db1.orders(id,order_type,customer_id,amount)
VALUES(1,101,100,100100);
INSERT INTO db1.orders(id,order_type,customer_id,amount)
VALUES(2,101,100,100300);
INSERT INTO db1.orders(id,order_type,customer_id,amount)
VALUES(3,101,101,120000);
INSERT INTO db1.orders(id,order_type,customer_id,amount)
VALUES(4,101,101,103000);
INSERT INTO db1.orders(id,order_type,customer_id,amount)
VALUES(5,102,101,100400);
INSERT INTO db1.orders(id,order_type,customer_id,amount)
VALUES(6,102,100,100020);
查看数据:
在 Mycat2数据客户端查询依然可以看到全部数据
5、创建 ER 表 ,在Mycat2数据客户端直接运行建表语句进行数据分片
CREATE TABLE db1.orders_detail(
`id` BIGINT NOT NULL AUTO_INCREMENT,
detail VARCHAR(2000),
order_id INT,
PRIMARY KEY(id)
)ENGINE=INNODB DEFAULT CHARSET=utf8
dbpartition BY mod_hash(order_id) tbpartition BY mod_hash(order_id)
tbpartitions 2 dbpartitions 1;
插入ER表数据
INSERT INTO db1.orders_detail(id,detail,order_id) VALUES(1,'detail1',1);
INSERT INTO db1.orders_detail(id,detail,order_id) VALUES(2,'detail1',2);
INSERT INTO db1.orders_detail(id,detail,order_id) VALUES(3,'detail1',3);
INSERT INTO db1.orders_detail(id,detail,order_id) VALUES(4,'detail1',4);
INSERT INTO db1.orders_detail(id,detail,order_id) VALUES(5,'detail1',5);
INSERT INTO db1.orders_detail(id,detail,order_id) VALUES(6,'detail1',6);
上述两表具有相同的分片算法,但是分片字段不相同Mycat2 在涉及这两个表的 join 分片字段等价关系的时候可以完成 join 的下推#Mycat2 无需指定 ER 表,是自动识别的,具体看分片算法的接口。
查看配置的表是否具有 ER 关系,使用
/*+ mycat:showErGroup{}*/
运行关联查询语句:
SELECT * FROM db1.orders o INNER JOIN db1.orders_detail od ON od.order_id=o.id;
标签:分库,orders,MyCat2,detail,order,db1,VALUES,分表,id
From: https://www.cnblogs.com/shiding/p/17119826.html