• Mycat2 分布式数据库中间件


    一.安装部署

    Mycat2目前还不支持直接获取Docker镜像,需要自己通过Dockerfile打包镜像,其实这也是为了开发者考虑,比如一些个性化功能,如自定义分片等

    Dockerfile
    1. FROM docker.io/adoptopenjdk/openjdk8:latest
    2. ENV AUTO_RUN_DIR ./mycat2
    3. ENV DEPENDENCE_FILE mycat2-1.20-jar-with-dependencies.jar
    4. ENV TEMPLATE_FILE mycat2-install-template-1.21.zip
    5. #设置阿里云源,下载快一点
    6. RUN sed -i "s@http://.*archive.ubuntu.com@http://mirrors.aliyun.com@g" /etc/apt/sources.list
    7. RUN sed -i "s@http://.*security.ubuntu.com@http://mirrors.aliyun.com@g" /etc/apt/sources.list
    8. RUN buildDeps='procps wget unzip' \
    9. && apt-get update \
    10. && apt-get install -y $buildDeps
    11. RUN wget -P $AUTO_RUN_DIR/ http://dl.mycat.org.cn/2.0/1.20-release/$DEPENDENCE_FILE \
    12. && wget -P $AUTO_RUN_DIR/ http://dl.mycat.org.cn/2.0/install-template/$TEMPLATE_FILE
    13. RUN cd $AUTO_RUN_DIR/ \
    14. && unzip $TEMPLATE_FILE \
    15. && ls -al . \
    16. && mv $DEPENDENCE_FILE mycat/lib/ \
    17. && chmod +x mycat/bin/* \
    18. && chmod 755 mycat/lib/* \
    19. && mv mycat /usr/local
    20. #copy mycat /usr/local/mycat/
    21. VOLUME /usr/local/mycat/conf
    22. VOLUME /usr/local/mycat/logs
    23. EXPOSE 8066 1984
    24. CMD ["/usr/local/mycat/bin/mycat", "console"]

    二.编译镜像 

    1. #如果执行目录不是Dockerfile所在目录,需要-f指定
    2. docker build -t mycat2:1.20 .

    三.创建容器

    1. docker run -d --name=mycat2 -p 8066:8066 -p 1984:1984 -v /usr/local/mycat/conf:/usr/local/mycat/conf -v /usr/local/mycat/logs:/usr/local/mycat/logs mycat2:1.20
    2. #会启动失败,因为数据库配置不对,要改数据库链接才行
    3. vi /usr/local/mycat/conf/datasources/prototypeDs.datasource.json
    4. #jdbc:mysql://192.168.88.192:3306
    5. # 复制容器内配置
    6. mkdir /usr/local/mycat
    7. cd /usr/local/mycat
    8. docker cp mycat2:/usr/local/mycat/conf .
    9. docker cp mycat2:/usr/local/mycat/logs .

    四.docker-compose.yml

    1. version: '3.3'
    2. services:
    3. mycat2:
    4. build:
    5. context: ./
    6. dockerfile: Dockerfile
    7. image: mycat2:1.20
    8. container_name: mycat2
    9. ports:
    10. - 8066:8066
    11. links:
    12. - mysql1
    13. - mysql2
    14. volumes:
    15. - /usr/local/mycat/conf:/usr/local/mycat/conf
    16. - /usr/local/mycat/logs:/usr/local/mycat/logs

    配置文件修改

    我们将要使用mycat2实现读写分离,所以前提是需要将数据库设置为主从复制模式(不然读的永远为空),3306端口为master,3307端口为slave

    数据源配置
    1. cd /usr/local/mycat/conf/datasources
    2. #从原生配置复制两个json文件
    3. [root@localhost datasources]# cp prototypeDs.datasource.json master01.datasource.json
    4. [root@localhost datasources]# cp prototypeDs.datasource.json slave01.datasource.json
    5. [root@localhost datasources]# ls
    6. master01.datasource.json prototypeDs.datasource.json slave01.datasource.json
    7. #master01.datasource.json
    8. {
    9. "dbType":"mysql",
    10. "idleTimeout":60000,
    11. "initSqls":[],
    12. "initSqlsGetConnection":true,
    13. "instanceType":"READ_WRITE",
    14. "maxCon":1000,
    15. "maxConnectTimeout":3000,
    16. "maxRetryCount":5,
    17. "minCon":1,
    18. "name":"master01",
    19. "password":"root",
    20. "type":"JDBC",
    21. "url":"jdbc:mysql://192.168.88.192:3306?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=UTF-8",
    22. "user":"root",
    23. "weight":0
    24. }
    25. #slave01.datasource.json
    26. {
    27. "dbType":"mysql",
    28. "idleTimeout":60000,
    29. "initSqls":[],
    30. "initSqlsGetConnection":true,
    31. "instanceType":"READ_WRITE",
    32. "maxCon":1000,
    33. "maxConnectTimeout":3000,
    34. "maxRetryCount":5,
    35. "minCon":1,
    36. "name":"slave01",
    37. "password":"root",
    38. "type":"JDBC",
    39. "url":"jdbc:mysql://192.168.88.192:3307?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=UTF-8",
    40. "user":"root",
    41. "weight":0
    42. }
    数据源集群配置
    1. #clusters/prototype.cluster.json
    2. {
    3. "clusterType":"MASTER_SLAVE",
    4. "heartbeat":{
    5. "heartbeatTimeout":1000,
    6. "maxRetry":3,
    7. "minSwitchTimeInterval":300,
    8. "slaveThreshold":0
    9. },
    10. "masters":[
    11. "master01" #写
    12. ],
    13. "replicas":[
    14. "slave01" #读
    15. ],
    16. "maxCon":200,
    17. "name":"prototype",
    18. "readBalanceType":"BALANCE_ALL",
    19. "switchType":"SWITCH"
    20. }
    物理库配置
    1. #schemas/matomo_tj.schema.json
    2. {
    3. # 物理库
    4. "schemaName": "matomo_tj",
    5. # 指向集群,或者数据源
    6. "targetName": "prototype"
    7. }
    Mycat2 登录用户配置
    1. #users/root.user.json
    2. {
    3. "dialect":"mysql",
    4. #ip 为 null,允许任意 ip 登录
    5. "ip":null,
    6. "password":"root",
    7. "transactionType":"proxy",
    8. "username":"root"
    9. }

    测试连接

    测试1:

    通过mycat2 执行插入,会发现master01,slave01都有相同的数据

    测试2:

    手动修改slave01数据,通过mycat2进行查询,会发现查询的数据为slave01的数据

    测试3:

    修改/clusters/prototype.cluster.json

    1. {
    2. "clusterType":"GARELA_CLUSTER", //改为集群模式
    3. "heartbeat":{
    4. "heartbeatTimeout":1000,
    5. "maxRetry":3,
    6. "minSwitchTimeInterval":300,
    7. "slaveThreshold":0
    8. },
    9. "masters":[ //多主模式
    10. "master01",
    11. "slave01"
    12. ],
    13. //"replicas":[
    14. // "slave01"
    15. //],
    16. "maxCon":200,
    17. "name":"prototype",
    18. "readBalanceType":"BALANCE_ALL",
    19. "switchType":"SWITCH"
    20. }

     关闭masters中任意服务器,然后通过mycat 8066进行数据插入操作,会发现剩下的那台服务器承接了write操作(HA)

    Zookeeper统一管理
    Zookeeper是个好东西,基本上涉及元数据的服务都可以使用它来实现或者辅助实现高可用集群,Mycat2也盯上了它

    其实在这里我们使用Zookeeper作为配置中心,存储Mycat2的配置,以及提供元数据锁和znode监听的功能,简单可以称其为:统一配置中心

    zookeeper docker安装配置:

    1. version: '3.3'
    2. services:
    3. zookeeper:
    4. container_name: zookeeper
    5. image: debezium/zookeeper
    6. ports:
    7. - 2181:2181

    我们 zookeeper客户端来可视化操作比较方便,工具下载:https://issues.apache.org/jira/secure/attachment/12436620/ZooInspector.zip

    解压后进入build,通过java -jar zookeeper-dev-ZooInspector.jar 启动窗口

    点击运行按钮输入zookeeper地址即可看到zookeeper的数据结构信息了:

    下面开始在mycat2的server.json文件配置zookeeper地址信息进行注册 

    1. #1、server.json改这两个信息就够了
    2. "mode":"cluster",
    3. "properties":{
    4. "zk_address":"192.168.88.192:2181"
    5. }
    6. #2、docker restart mycat2
    7. #3、使用ZooInspector登录该zk,编辑里面的mycat配置即可,除了server级别配置,其他配置schema,user,cache,sequence,datasource,cluster.都可以实现热更新,在ZK里编辑相当于直接更改配置文件,暂时无法自动创建物理库,物理表.

    分库分表
    概念
    分库分表就是为了解决由于数据量过大而导致数据库性能降低的问题,将原来独立的数据库拆分成若干数据库组成,将数据大表分成若干数据表组成,使得单一数据库、单一数据表的数据量变小,从而达到提升数据库性能的目的。而且随着微服务这种架构的兴起,我们应用从一个完整的大的应用,切分为很多可以独立提供服务的小应用,每个应用都有独立的数据库。数据的切分分为两种:

    l **垂直切分:**按照业务模块进行切分,将不同模块的表切分到不同的数据库中。

    l 水平切分:将一张大表按照一定的切分规则,按照行切分到不同的表或者不同的库中

    mycat2分库分表包括两种方式:

    SQL脚本命令分库分表,同时会在schemas下生成对应的json文件
    schemas下通过配置的方式进行分库分表
    广播表(全局表)
    这个其实不属于分库分表的范畴,只是对于分库分表来说,有些数据是公共的,比如数据字典,在每个库中都需要相同的数据

    顾名思义,大喇叭声音谁都听得见,所有库表都会收到相同数据,我们这里使用单一节点,就两个数据源,master01,master02(注意这两个库不要存在主从复制设置,或者在之前的slave库执行:stop slave;) 

    数据源master01.datasource.json

    1. {
    2. "dbType":"mysql",
    3. "idleTimeout":60000,
    4. "initSqls":[],
    5. "initSqlsGetConnection":true,
    6. "instanceType":"READ_WRITE",
    7. "maxCon":1000,
    8. "maxConnectTimeout":3000,
    9. "maxRetryCount":5,
    10. "minCon":1,
    11. "name":"master01",
    12. "password":"root",
    13. "type":"JDBC",
    14. "url":"jdbc:mysql://192.168.88.192:3306/matomo_tj?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=UTF-8",
    15. "user":"root",
    16. "weight":0
    17. }

     数据源master02.datasource.json

    1. {
    2. "dbType":"mysql",
    3. "idleTimeout":60000,
    4. "initSqls":[],
    5. "initSqlsGetConnection":true,
    6. "instanceType":"READ_WRITE",
    7. "maxCon":1000,
    8. "maxConnectTimeout":3000,
    9. "maxRetryCount":5,
    10. "minCon":1,
    11. "name":"master02",
    12. "password":"root",
    13. "type":"JDBC",
    14. "url":"jdbc:mysql://192.168.137.128:3307/matomo_tj?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=UTF-8",
    15. "user":"root",
    16. "weight":0
    17. }

    集群c0.cluster.json

    1. {
    2. "clusterType":"SINGLE_NODE",
    3. "heartbeat":{
    4. "heartbeatTimeout":1000,
    5. "maxRetry":3,
    6. "minSwitchTimeInterval":300,
    7. "slaveThreshold":0
    8. },
    9. "masters":[
    10. "master01"
    11. ],
    12. "maxCon":200,
    13. "name":"c0",
    14. "readBalanceType":"BALANCE_ALL",
    15. "switchType":"SWITCH"
    16. }

     集群c1.cluster.json

    1. {
    2. "clusterType":"SINGLE_NODE",
    3. "heartbeat":{
    4. "heartbeatTimeout":1000,
    5. "maxRetry":3,
    6. "minSwitchTimeInterval":300,
    7. "slaveThreshold":0
    8. },
    9. "masters":[
    10. "master02"
    11. ],
    12. "maxCon":200,
    13. "name":"c1",
    14. "readBalanceType":"BALANCE_ALL",
    15. "switchType":"SWITCH"
    16. }

     登录mycat2,创建逻辑库,广播表,并插入数据,会发现在master01,master02都会有相同的库表结构及数据

    1. CREATE DATABASE db1;
    2. USE db1;
    3. CREATE TABLE `travelrecord` (
    4. `id` BIGINT NOT NULL auto_increment,
    5. `user_id` VARCHAR ( 100 ) DEFAULT NULL,
    6. `traveldate` date DEFAULT NULL,
    7. `fee` DECIMAL ( 10, 0 ) DEFAULT NULL,
    8. `days` INT DEFAULT NULL,
    9. `blob` LONGBLOB,
    10. PRIMARY KEY ( `id` ),
    11. KEY `id` ( `id` )
    12. ) ENGINE = INNODB DEFAULT CHARSET = utf8 BROADCAST;
    13. INSERT INTO `db1`.`travelrecord` (`id`, `user_id`, `traveldate`, `fee`, `days`, `blob`) VALUES (1, '1', '2022-08-12', 1, 1, NULL);
    14. INSERT INTO `db1`.`travelrecord` (`id`, `user_id`, `traveldate`, `fee`, `days`, `blob`) VALUES (2, '2', '2022-08-12', 2, 2, NULL);

     分片表

    mycat2分片可以使用SQL脚本和schema配置,内置Hash分片策略,targetIndexdbIndextableIndex总是从0开始计算,支持groovy运算生成目标名,库名,表名 

    Hash分片(SQL)

    官网截图,可惜有个错误:YYYYDD应该是按年日哈希

    需求:进行站点访问统计,按访问年份分库,按访问站点分表

    分析:这个地方需要用到取模哈(MOD_HASH)希和按年月哈希(YYYYMM)

    登录mycat2,创建逻辑库,分片表,并插入数据,即将采用的最终策略按如下“斜体”计算

    MOD_HASH

    分库键和分表键是同键

    分表下标=分片值%(分库数量*分表数量)

    分库下标=分表下标/分表数量

    分库键和分表键是不同键

    分表下标=分片值%分表数量

    分库下标=分表下标%分库数量

    YYYYMM

    仅用于分库

    (YYYY*12+MM)%分库数

    1. DROP DATABASE db2;
    2. CREATE DATABASE db2;
    3. USE db2;
    4. DROP TABLE IF EXISTS `matomo_log_visit_material`;
    5. CREATE TABLE `matomo_log_visit_material` (
    6. `idvisit` BIGINT(100) NOT NULL AUTO_INCREMENT COMMENT '访问记录主键',
    7. `idsite` bigint(20) NULL DEFAULT NULL COMMENT '站点id',
    8. `user_id` tinytext CHARACTER SET utf8 COLLATE utf8_bin NULL COMMENT '用户id',
    9. `visit_first_action_time` datetime NULL DEFAULT NULL COMMENT '访问的第一个动作的日期时间',
    10. `visit_total_time` int(11) NULL DEFAULT NULL COMMENT '停留总时间',
    11. `visit_goal_buyer` tinyint(1) NULL DEFAULT NULL COMMENT '是否购买',
    12. `referer_type` tinyint(1) NULL DEFAULT NULL COMMENT '用户来源',
    13. `location_ip` varbinary(16) NULL DEFAULT NULL COMMENT '访问者ip',
    14. PRIMARY KEY (`idvisit`) USING BTREE
    15. ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin COMMENT = '用户访问数据素材表' ROW_FORMAT = COMPACT dbpartition by YYYYMM (visit_first_action_time) dbpartitions 8
    16. tbpartition by MOD_HASH (idsite) tbpartitions 3;
    17. DELETE FROM `db2`.`matomo_log_visit_material`;
    18. INSERT INTO `db2`.`matomo_log_visit_material` (`idsite`, `user_id`, `visit_first_action_time`, `visit_total_time`, `visit_goal_buyer`, `referer_type`, `location_ip`) VALUES (1, '1', '2022-01-12 16:32:13', 1, 1, 1, NULL);
    19. INSERT INTO `db2`.`matomo_log_visit_material` (`idsite`, `user_id`, `visit_first_action_time`, `visit_total_time`, `visit_goal_buyer`, `referer_type`, `location_ip`) VALUES (2, '2', '2021-02-12 16:32:32', 2, 2, 2, NULL);
    20. INSERT INTO `db2`.`matomo_log_visit_material` (`idsite`, `user_id`, `visit_first_action_time`, `visit_total_time`, `visit_goal_buyer`, `referer_type`, `location_ip`) VALUES (3, '1', '2020-03-12 16:32:13', 1, 1, 1, NULL);
    21. INSERT INTO `db2`.`matomo_log_visit_material` (`idsite`, `user_id`, `visit_first_action_time`, `visit_total_time`, `visit_goal_buyer`, `referer_type`, `location_ip`) VALUES (1, '2', '2019-04-12 16:32:32', 2, 2, 2, NULL);
    22. INSERT INTO `db2`.`matomo_log_visit_material` (`idsite`, `user_id`, `visit_first_action_time`, `visit_total_time`, `visit_goal_buyer`, `referer_type`, `location_ip`) VALUES (2, '1', '2018-05-12 16:32:13', 1, 1, 1, NULL);
    23. INSERT INTO `db2`.`matomo_log_visit_material` (`idsite`, `user_id`, `visit_first_action_time`, `visit_total_time`, `visit_goal_buyer`, `referer_type`, `location_ip`) VALUES (3, '2', '2017-06-12 16:32:32', 2, 2, 2, NULL);
    24. INSERT INTO `db2`.`matomo_log_visit_material` (`idsite`, `user_id`, `visit_first_action_time`, `visit_total_time`, `visit_goal_buyer`, `referer_type`, `location_ip`) VALUES (1, '1', '2016-07-12 16:32:13', 1, 1, 1, NULL);
    25. INSERT INTO `db2`.`matomo_log_visit_material` (`idsite`, `user_id`, `visit_first_action_time`, `visit_total_time`, `visit_goal_buyer`, `referer_type`, `location_ip`) VALUES (2, '2', '2015-08-12 16:32:32', 2, 2, 2, NULL);
    26. INSERT INTO `db2`.`matomo_log_visit_material` (`idsite`, `user_id`, `visit_first_action_time`, `visit_total_time`, `visit_goal_buyer`, `referer_type`, `location_ip`) VALUES (3, '1', '2014-09-12 16:32:13', 1, 1, 1, NULL);
    27. INSERT INTO `db2`.`matomo_log_visit_material` (`idsite`, `user_id`, `visit_first_action_time`, `visit_total_time`, `visit_goal_buyer`, `referer_type`, `location_ip`) VALUES (1, '2', '2013-10-12 16:32:32', 2, 2, 2, NULL);
    28. INSERT INTO `db2`.`matomo_log_visit_material` (`idsite`, `user_id`, `visit_first_action_time`, `visit_total_time`, `visit_goal_buyer`, `referer_type`, `location_ip`) VALUES (2, '2', '2012-11-12 16:32:32', 2, 2, 2, NULL);
    29. INSERT INTO `db2`.`matomo_log_visit_material` (`idsite`, `user_id`, `visit_first_action_time`, `visit_total_time`, `visit_goal_buyer`, `referer_type`, `location_ip`) VALUES (3, '2', '2011-12-12 16:32:32', 2, 2, 2, NULL);

    我们拿第一条数据来看:

    分库按(2022*12+1)% 8 = 1,数据库下标为1

    分表按1%3 = 1,数据表下标为1

    Hash分片(Schema)

    其实,我们通过SQL脚本执行的分片策略,会在schemas下生成对应的json配置文件,如上面两节我们就可以看到对应的文件:

    打开可以看到,其实就是SQL脚本解析生成的: 

    1. {
    2. "customTables":{},
    3. "globalTables":{},
    4. "normalTables":{},
    5. "schemaName":"db2",
    6. "shardingTables":{
    7. "matomo_log_visit_material":{
    8. "createTableSQL":"CREATE TABLE db2.`matomo_log_visit_material` (\n\t`idvisit` BIGINT(100) NOT NULL AUTO_INCREMENT COMMENT '访问记录主键',\n\t`idsite` bigint(20) NULL DEFAULT NULL COMMENT '站点id',\n\t`user_id` tinytext CHARACTER SET utf8 COLLATE utf8_bin NULL COMMENT '用户id',\n\t`visit_first_action_time` datetime NULL DEFAULT NULL COMMENT '访问的第一个动作的日期时间',\n\t`visit_total_time` int(11) NULL DEFAULT NULL COMMENT '停留总时间',\n\t`visit_goal_buyer` tinyint(1) NULL DEFAULT NULL COMMENT '是否购买',\n\t`referer_type` tinyint(1) NULL DEFAULT NULL COMMENT '用户来源',\n\t`location_ip` varbinary(16) NULL DEFAULT NULL COMMENT '访问者ip',\n\tPRIMARY KEY USING BTREE (`idvisit`)\n) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = COMPACT COMMENT '用户访问数据素材表'\nDBPARTITION BY YYYYMM(visit_first_action_time) DBPARTITIONS 8\nTBPARTITION BY MOD_HASH(idsite) TBPARTITIONS 3",
    9. "function":{
    10. "properties":{
    11. "dbNum":"8",
    12. "mappingFormat":"c${targetIndex}/db2_${dbIndex}/matomo_log_visit_material_${tableIndex}",
    13. "tableNum":"3",
    14. "tableMethod":"MOD_HASH(idsite)",
    15. "storeNum":2,
    16. "dbMethod":"YYYYMM(visit_first_action_time)"
    17. },
    18. "ranges":{}
    19. },
    20. "partition":{
    21. },
    22. "shardingIndexTables":{}
    23. }
    24. },
    25. "views":{}
    26. }

  • 相关阅读:
    List 模拟实现
    Python(Web时代)—— Django的模板
    Gson解析会丢失默认属性值
    UniParser:异构日志数据的统一日志解析器
    深入体验Java Web开发内目-核心基础 PDF篇
    C语言 位操作符 >> << & | ^
    NewStarCTF2023week2-base!(base低位隐写)
    Kubernetes控制平面组件:Scheduler调度器
    《剑指offer第二版》面试题14:剪绳子
    tomcat
  • 原文地址:https://blog.csdn.net/yuanzelin8/article/details/133906008